แก้ไข

แชร์ผ่าน


How to separate strings using String.Split in C#

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. It's also used to split strings on other specific characters or strings.

Note

The C# examples in this article run in the Try.NET inline code runner and playground. Select the Run button to run an example in an interactive window. Once you execute the code, you can modify it and run the modified code by selecting Run again. The modified code either runs in the interactive window or, if compilation fails, the interactive window displays all C# compiler error messages.

String.Split examples

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)
{
    System.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++)
{
    System.Console.WriteLine($"Index {i}: <{words[i]}>");
}

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)
{
    System.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.

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";
System.Console.WriteLine($"Original text: '{text}'");

string[] words = text.Split(delimiterChars);
System.Console.WriteLine($"{words.Length} words in text:");

foreach (var word in words)
{
    System.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";
System.Console.WriteLine($"Original text: '{text}'");

string[] words = text.Split(delimiterChars);
System.Console.WriteLine($"{words.Length} words in text:");

foreach (var word in words)
{
    System.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";
System.Console.WriteLine($"Original text: '{text}'");

string[] words = text.Split(separatingStrings, System.StringSplitOptions.RemoveEmptyEntries);
System.Console.WriteLine($"{words.Length} substrings in text:");

foreach (var word in words)
{
    System.Console.WriteLine(word);
}

Use GitHub Copilot to split a string

You can use GitHub Copilot in your IDE to generate code to split strings using String.Split in C#.

If you're using Visual Studio 2022 version 17.8 or later, you can try the AI-driven GitHub Copilot in Visual Studio to generate code to split an input string into substrings based on one or more delimiters. Submit your question as a prompt in the Copilot chat window, as in the following example. You can also submit prompts using inline chat in the editor window itself.

Note

GitHub Copilot is powered by AI, so surprises and mistakes are possible. Make sure to verify any generated code or suggestions. For more information about the general use of GitHub Copilot, product impact, human oversight, and privacy, see GitHub Copilot FAQs.

The following text shows an example prompt for Copilot Chat:

Generate C# code to use Split.String split a string into substrings. Input string is "You win some. You lose some." Delimiters are space and period. Provide example output.

You can customize the prompt to use strings and delimiters per your requirements.

You can use chat features, such as slash commands, references to files, methods, or classes, and threads, to set intent and get better answers with scoped context. For an existing file that's open in the IDE, you can prompt GitHub Copilot using inline chat with /generate code to split string1 in #Filename by delimiter spaces.

The following output shows an example Copilot Chat response:

Here is an example of how you can use the Split method in C# to split the string "You win some. You lose some." using space and period as delimiters:

using System;

class Program
{
    static void Main()
    {
        string input = "You win some. You lose some.";
        char[] delimiters = new char[] { ' ', '.' };
        string[] substrings = input.Split(delimiters, StringSplitOptions.RemoveEmptyEntries);

        foreach (string substring in substrings)
        {
            Console.WriteLine(substring);
        }
    }
}

**Example Output**
You
win
some
You
lose
some

When Copilot returns a code block, the response includes options to copy the code, insert the code into a new file, or preview the code output.

Note

Your results might be different from what's shown in the example responses. AI models are non-deterministic, which means that they can return different responses when asked the same question. This might be due to additional learning and adaption over time, language variation, changes in context, such as your chat history, and more.

Screenshot that shows using GitHub Copilot Chat in Visual Studio to split a string into substrings.

For more information, see:

See also