split a string into an array of words in csharp

To split a string into an array of words in C#, you can use the Split() method provided by the String class. This method splits the string into an array of substrings based on a specified delimiter character or a set of delimiter characters.

In the following example, we split a string into an array of words using space as the delimiter character:

main.cs
string sentence = "The quick brown fox jumps over the lazy dog";
string[] words = sentence.Split(' '); // split using space delimiter
134 chars
3 lines

The resulting words array contains the following elements:

main.cs
["The", "quick", "brown", "fox", "jumps", "over", "the", "lazy", "dog"]
72 chars
2 lines

You can also split a string using multiple delimiter characters, such as space and comma, by passing an array of delimiter characters to the Split() method:

main.cs
string sentence = "The quick brown fox, jumps over the lazy dog";
char[] delimiters = { ' ', ',' };
string[] words = sentence.Split(delimiters);
145 chars
4 lines

The resulting words array contains the following elements:

main.cs
["The", "quick", "brown", "fox", "", "jumps", "over", "the", "lazy", "dog"]
76 chars
2 lines

Note that the second element in the array is an empty string because there is a comma immediately after the word "fox".

related categories

gistlibby LogSnag