C# String Split
The Split()
method in C# is used to break a string into an array of substrings, based on one or more delimiters.
Key Topics
1. Basic Split
Example: Splitting a Sentence into Words
string sentence = "Hello, World! Welcome to C#.";
string[] words = sentence.Split(' ');
foreach (string word in words)
{
Console.WriteLine(word);
}
Output:
Hello,
World!
Welcome
to
C#.
2. Using Multiple Delimiters
Example: Splitting with Multiple Characters
string data = "apple;banana,orange|grape";
char[] separators = { ';', ',', '|' };
string[] fruits = data.Split(separators);
foreach (string fruit in fruits)
{
Console.WriteLine(fruit);
}
3. StringSplitOptions
Example: Removing Empty Entries
string values = "one,,two,,,three";
string[] result = values.Split(
new char[] { ',' },
StringSplitOptions.RemoveEmptyEntries);
foreach (string val in result)
{
Console.WriteLine(val);
}
Output:
one
two
three
Key Takeaways
- The
Split()
method divides a string into an array based on specified delimiters. - You can use multiple delimiters by providing an array of characters.
StringSplitOptions
allows you to control how the split operation handles empty entries.