split a string into an array of substrings in csharp

To split a string into an array of substrings in C#, you can use the Split method, which is available on the string class. This method takes a delimiter as an argument, and returns an array of substrings.

Here's an example:

main.cs
string myString = "Hello, world!";
string[] myArray = myString.Split(',');

// myArray now contains ["Hello", " world!"]
121 chars
5 lines

In this example, we're splitting the string myString using a , as the delimiter. The resulting array myArray contains two elements: "Hello" and " world!".

You can also split a string using multiple delimiters by passing an array of delimiters to the Split method, like this:

main.cs
string myString = "apples, bananas; oranges";
char[] delimiters = new char[] { ',', ';' };
string[] myArray = myString.Split(delimiters);

// myArray now contains ["apples", " bananas", " oranges"]
198 chars
6 lines

In this example, we're splitting the string myString using both , and ; as delimiters. The resulting array myArray contains three elements: "apples", " bananas", and " oranges". Note that the spaces after the commas and semicolons are included in the resulting substrings. If you want to remove leading or trailing spaces from each substring, you can call the Trim method on each element of the resulting array.

gistlibby LogSnag