Белешка
Приступ овој страници захтева ауторизацију. Можете покушати да се пријавите или промените директоријуме.
Приступ овој страници захтева ауторизацију. Можете покушати да промените директоријуме.
The String.Split method creates an array of substrings by splitting the input string based on one or more delimiters. This method is often the easiest way to separate a string on word boundaries.
Tip
You can use AI assistance to split a string.
Split a string into words
The following code splits a common phrase into an array of strings for each word.
string phrase = "The quick brown fox jumps over the lazy dog.";
string[] words = phrase.Split(' ');
foreach (var word in words)
{
Console.WriteLine($"<{word}>");
}
Every instance of a separator character produces a value in the returned array. Since arrays in C# are zero-indexed, each string in the array is indexed from 0 to the value returned by the Array.Length property minus 1:
string phrase = "The quick brown fox jumps over the lazy dog.";
string[] words = phrase.Split(' ');
for (int i = 0; i < words.Length; i++)
{
Console.WriteLine($"Index {i}: <{words[i]}>");
}
The String.Split has many overloads. These overloads customize the behavior for splitting strings:
- You can specify separators as
charvalues orstringvalues. - You can specify one separator or multiple separators. If you specify multiple separators, they must all be the same type (either
charorstring). - You can specify the maximum number of substrings to return.
- You can specify if repeated separator characters are ignored, or produce empty substrings in the return value.
- You can specify if leading and trailing whitespace is removed from the returned substrings.
The remaining examples use different overloads to show each of these behaviors.
For more information about indices, see the Explore indexes and ranges article.
Specify multiple separators
String.Split can use multiple separator characters. The following example uses spaces, commas, periods, colons, and tabs as separating characters, which are passed to Split in an array. The loop at the bottom of the code displays each of the words in the returned array.
char[] delimiterChars = [' ', ',', '.', ':', '\t'];
string text = "one\ttwo three:four,five six seven";
Console.WriteLine($"Original text: '{text}'");
string[] words = text.Split(delimiterChars);
Console.WriteLine($"{words.Length} words in text:");
foreach (var word in words)
{
Console.WriteLine($"<{word}>");
}
Consecutive instances of any separator produce the empty string in the output array:
char[] delimiterChars = [' ', ',', '.', ':', '\t'];
string text = "one\ttwo :,five six seven";
Console.WriteLine($"Original text: '{text}'");
string[] words = text.Split(delimiterChars);
Console.WriteLine($"{words.Length} words in text:");
foreach (var word in words)
{
Console.WriteLine($"<{word}>");
}
String.Split can take an array of strings (character sequences that act as separators for parsing the target string, instead of single characters).
string[] separatingStrings = ["<<", "..."];
string text = "one<<two......three<four";
Console.WriteLine($"Original text: '{text}'");
string[] words = text.Split(separatingStrings, StringSplitOptions.RemoveEmptyEntries);
Console.WriteLine($"{words.Length} substrings in text:");
foreach (var word in words)
{
Console.WriteLine(word);
}
Limit output size
The following example shows how to limit the output to the first four substrings in the source string.
string phrase = "The quick brown fox jumps over the lazy dog.";
string[] words = phrase.Split(' ', 4, StringSplitOptions.None);
foreach (var word in words)
{
Console.WriteLine($"<{word}>");
}
Remove empty substrings
Consecutive separator characters produce the empty string as a value in the returned array. You can see how an empty string is created in the following example, which uses the space character as a separator.
string phrase = "The quick brown fox jumps over the lazy dog.";
string[] words = phrase.Split(' ');
foreach (var word in words)
{
Console.WriteLine($"<{word}>");
}
This behavior makes it easier for formats like comma-separated values (CSV) files representing tabular data. Consecutive commas represent a blank column.
You can pass an optional StringSplitOptions.RemoveEmptyEntries parameter to exclude any empty strings in the returned array. For more complicated processing of the returned collection, you can use LINQ to manipulate the result sequence.
Trim whitespace
The following example shows the effect of trimming entries:
string numerals = "1, 2, 3, 4, 5, 6, 7, 8, 9, 10";
string[] words = numerals.Split(',', StringSplitOptions.TrimEntries);
Console.WriteLine("Trimmed entries:");
foreach (var word in words)
{
Console.WriteLine($"<{word}>");
}
words = numerals.Split(',', StringSplitOptions.None);
Console.WriteLine("Untrimmed entries:");
foreach (var word in words)
{
Console.WriteLine($"<{word}>");
}
The untrimmed entries have extra whitespace before the numerals.
Use AI to split a string
You can use AI tools, such as GitHub Copilot, to generate code to split strings using String.Split in C#. You can customize the prompt to use strings and delimiters per your requirements.
The following text shows an example prompt for Copilot Chat:
Generate C# code to parse and split CSV-style data from user input or external export that isn't well formed.
The input string may contain mixed delimiters (commas, semicolons), inconsistent spacing and empty entries.
Parse the string: accept all valid separators, remove any empty values and trim whitespace from all entries.
Return a clean list of values.
Show example output for the string: " apples, oranges ; bananas, , ;pears".
Review Copilot's suggestions before applying them.
For more information, see Copilot FAQs.