Home >Backend Development >C++ >How Can I Split a String in C# Using a Single Character or a String as a Delimiter?

How Can I Split a String in C# Using a Single Character or a String as a Delimiter?

Barbara Streisand
Barbara StreisandOriginal
2025-01-11 07:40:421029browse

How Can I Split a String in C# Using a Single Character or a String as a Delimiter?

Splitting a String with a Delimiter

In C#, the Split() method enables you to split a string into substrings based on a specified delimiter. However, by default, it only accepts a single character as a delimiter.

Splitting with a String Delimiter

To split a string using a string as a delimiter, you can specify the delimiter as an array within the Split() method. For example:

string[] tokens = str.Split(new[] { "is Marco and" }, StringSplitOptions.None);

In this case, str is the input string, and tokens will contain an array of two substrings:

  • tokens[0]: "My name"
  • tokens[1]: "I'm from Italy"

Simplifying for Single-Character Delimiters

If you are splitting the string using a single character delimiter, such as a comma ,, you can simplify the code as follows:

string[] tokens = str.Split(',');

This approach is more concise, especially when dealing with simple delimiters.

The above is the detailed content of How Can I Split a String in C# Using a Single Character or a String as a Delimiter?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn