The Split
method of the string
class in C# is used to split a string into an array of substrings based on a delimiter string.
To split a string by another string in C#, you can use the Split
method of the string
class. Here is an example of how to use it:
1 2 3 4 5 6 7 8 9 |
string input = "This is a test string"; string[] parts = input.Split(' '); foreach (string part in parts) { Console.WriteLine(part); } |
This code will split the input string into an array of substrings, using the space character as the delimiter. The output will be:
1 2 3 4 5 6 7 |
This is a test string |
You can use any string as the delimiter, not just a single character. For example:
1 2 3 4 5 6 7 8 9 |
string input = "This is a test string"; string[] parts = input.Split("test"); foreach (string part in parts) { Console.WriteLine(part); } |
This code will split the input string into an array of substrings, using the string “test” as the delimiter. The output will be:
1 2 3 4 |
This is a string |
You can also specify a limit for the number of substrings to return. For example:
1 2 3 4 5 6 7 8 9 |
string input = "This is a test string"; string[] parts = input.Split(new string[] { " " }, 2); foreach (string part in parts) { Console.WriteLine(part); } |
This code will split the input string into an array of substrings, using the space character as the delimiter, and will return a maximum of 2 substrings. The output will be:
1 2 3 4 |
This is a test string |