Skip to Content
C# Cookbook
book

C# Cookbook

by Stephen Teilhet, Jay Hilyard
January 2004
Beginner to intermediate
864 pages
22h 18m
English
O'Reilly Media, Inc.
Content preview from C# Cookbook

2.18. Extracting Items from a Delimited String

Problem

You have a string, possibly from a text file, which is delimited by one or more characters. You need to retrieve each piece of delimited information as easily as possible.

Solution

Using the Split instance method on the string class, we can place the delimited information into an array in as little as a single line of code. For example:

string delimitedInfo = "100,200,400,3,67";
string[] discreteInfo = delimitedInfo.Split(new char[1] {','});

foreach (string Data in discreteInfo)
    Console.WriteLine(Data);

The string array discreteInfo holds the following values:

100
200
400
3
67

Discussion

The Split method, like most methods in the string class, is simple to use. This method returns a string array with each element containing one discrete piece of the delimited text split on the delimiting character(s).

In the Solution, the string delimitedInfo was comma-delimited. However, it could have been delimited by any type of character or even by more than one character. When there is more than one type of delimiter, use code like the following:

string[] discreteInfo = delimitedInfo.Split(new char[3] {',', ':', ' '});

This line splits the delimitedInfo string whenever one of the three delimiting characters (comma, colon, or space character) is found.

The Split method is case-sensitive. To split a string on the letter "a" in a case-insensitive manner, use code like the following:

string[] discreteInfo = delimitedInfo.Split(new char[1] {'a', 'A'}); ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

C# Cookbook

C# Cookbook

Joe Mayo
C# Cookbook, 2nd Edition

C# Cookbook, 2nd Edition

Jay Hilyard, Stephen Teilhet
ASP.NET Cookbook

ASP.NET Cookbook

Michael A Kittel, Geoffrey T. LeBlond

Publisher Resources

ISBN: 0596003390Supplemental ContentCatalog PageErrata