Manipulating Strings in C#—Splitting a String
Microsoft .NET Framework, ASP.NET, Visual C# (CSharp, C Sharp, C-Sharp) Developer Training, Visual Studio
Splitting a String
Suppose you have a list of names in a single string, with each name separated by a comma. Then suppose you wanted to extract each name from the string. The hard way to do this is to scan all the characters for commas, then copy the characters before the comma to another string. The easy way is to use the Split function in the string class. You can tell the Split function what character or characters to use as delimiters—the Split function then creates substrings for each segment before and after each delimiter. The Split function returns an array of strings.
To split strings into an array of substrings:
- 1. Type
string[] pieces, wherepiecesis the name of the string array variable that will hold all the segments resulting from the split.
- 2. Type
= str.Split(',');wherestris the name of the string variable containing the buffer you wish to split, and','is the delimiter character (Figure 4.48).
Tips
- You can specify more than one delimiter to use in the split. For example if your string contains
"Apples,Bananas,Grapes; Rice,Potatoes,Noodles;"you can specify both a single quote and a semicolon as delimiter characters (Figure 4.49).
- You can specify more than one delimiter to use in the split. For example if your string contains

- Figure 4.49. The
Splitfunction is flexible enough to split based on any number of delimiters. In this example the function splits the original string each time it finds a comma or a semicolon.
- You can omit the delimiter character altogether, in which case the
Splitfunction treats spaces and carriage returns as delimiter characters (Figure 4.50).
- You can omit the delimiter character altogether, in which case the

- Figure 4.50. If you don't specify a delimiter character,
Splituses spaces and carriage returns as delimiters.
- If the
Splitfunction finds two delimiter characters next to each other then the function returns an empty string to represent the segment between the two delimiters (Figure 4.51).
- If the

- Figure 4.51. When you have two delimiters next to each other, in this case a space and a carriage return, you end up with an empty string.
- If you specify one or more delimiter characters in the
Splitfunction, and theSplitfunction doesn't find any of the characters in the string, theSplitfunction returns an array of one element in which the element is the entire original string (Figure 4.52).
- If you specify one or more delimiter characters in the

- Figure 4.52. If
Splitdoesn't find the delimiter you specified, it simply returns an array with a single element containing the original string.
|


