Home > Backend Development > C++ > How to Split a String Using a String Delimiter in C#?

How to Split a String Using a String Delimiter in C#?

DDD
Release: 2025-01-11 09:39:42
Original
515 people have browsed it

How to Split a String Using a String Delimiter in C#?

How to split a string using string delimiter in C#

When dealing with complex strings, it is often necessary to split them into smaller components. While the .Split() method in C# works with single character delimiters, it can be tricky when you need to split by string delimiters.

Let us consider the following example string:

<code>"My name is Marco and I'm from Italy"</code>
Copy after login

To split this string by the delimiter "is Marco and" you can use:

<code>string[] tokens = str.Split(new[] { "is Marco and" }, StringSplitOptions.None);</code>
Copy after login

In this code, we pass an array containing the delimiter string as the first parameter. The StringSplitOptions.None parameter ensures that the separator is treated as a single string rather than multiple single characters.

As a result, the tokens array will contain two elements:

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

If the separator is a single character, a simpler code form can be used:

<code>string[] tokens = str.Split(',');</code>
Copy after login

This will split the string by comma characters.

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

source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template