Coder Perfect

In C#, how do I use a multi-character delimiter to split a string?


What if I wish to split a string using a word as a delimiter?

This is an example of a sentence.

I’d like to split it and get it. This is followed by a sentence.

I can send in a string as a delimiter in Java, but how do I do it in C#?

Asked by Saobi

Solution #1

The following is an example from the documentation:

string source = "[stop]ONE[stop][stop]TWO[stop][stop][stop]THREE[stop][stop]";
string[] stringSeparators = new string[] {"[stop]"};
string[] result;

// ...
result = source.Split(stringSeparators, StringSplitOptions.None);

foreach (string s in result)
    Console.Write("'{0}' ", String.IsNullOrEmpty(s) ? "<>" : s);

Answered by bruno conde

Solution #2

You can do something like this with the Regex.Split method:

Regex regex = new Regex(@"\bis\b");
string[] substrings = regex.Split("This is a sentence");

foreach (string match in substrings)
   Console.WriteLine("'{0}'", match);

Edit: This answers the question you posed. Because a regular String.Split would split on the “is” at the end of the word “This,” I used the Regex approach and added the word boundaries around the “is.” However, if you merely made a mistake and created this example, String.Split will definitely sufficient.

Answered by IRBMe

Solution #3

This simplifies the implementation, based on previous comments to this post:)

namespace System
    public static class BaseTypesExtensions
        /// <summary>
        /// Just a simple wrapper to simplify the process of splitting a string using another string as a separator
        /// </summary>
        /// <param name="s"></param>
        /// <param name="pattern"></param>
        /// <returns></returns>
        public static string[] Split(this string s, string separator)
            return s.Split(new string[] { separator }, StringSplitOptions.None);


Answered by eka808

Solution #4

string s = "This is a sentence.";
string[] res = s.Split(new string[]{ " is " }, StringSplitOptions.None);

for(int i=0; i<res.length; i++)

EDIT: To retain the fact that you just want the word “is” deleted from the sentence and the word “this” to remain intact, the “is” is padded on both sides with spaces in the array.

Answered by ahawker

Solution #5

…In short:

string[] arr = "This is a sentence".Split(new string[] { "is" }, StringSplitOptions.None);

Answered by ParPar

Post is based on