How to: Parse Strings Using the Split Method (C# Programming Guide)
The following code example demonstrates how a string can be parsed using the System.String.Split method. This method works by returning an array of strings, where each element is a word. As input, Split takes an array of chars that indicate which characters are to be used as delimiters. In this example, spaces, commas, periods, colons, and tabs are used. An array containing these delimiters is passed to Split, and each word in the sentence is displayed separately using the resulting array of strings.
Example
class TestStringSplit
{
static void Main()
{
char[] delimiterChars = { ' ', ',', '.', ':', '\t' };
string text = "one\ttwo three:four,five six seven";
System.Console.WriteLine("Original text: '{0}'", text);
string[] words = text.Split(delimiterChars);
System.Console.WriteLine("{0} words in text:", words.Length);
foreach (string s in words)
{
System.Console.WriteLine(s);
}
}
}
Output
Original text: 'one two three:four,five six seven' 7 words in text: one two three four five six seven
See Also
Concepts
Other Resources
Strings (C# Programming Guide)
.NET Framework Regular Expressions
.NET Programming in C++