246

What if I want to split a string using a delimiter that is a word?

For example, This is a sentence.

I want to split on is and get This and a sentence.

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

11 Answers 11

297

https://learn.microsoft.com/en-us/dotnet/api/system.string.split

Example from the docs:

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);
}
Sign up to request clarification or add additional context in comments.

6 Comments

This actually returns: 'Th' ' ' ' a sentence' with the example given in the question. Perhaps this is what he actually wants, but it's not what he specified.
This is just an example ... The point is: There is a String.Split that takes strings as delimiters.
Yes, but it doesn't do what the question specifies. You have to use something a bit more clever to get the output specified. Now, whether what the question specified is actually what the asker wants is a different question, but the question asked here can't be answered trivially with just String.Split.
Still doesn't quite work. If you include the spaces in the word to split, they're not included in the output. If you examine the example given in the question, you'll notice that they do in fact include the spaces. Splitting on " is " would give you "This" and "a sentence" rather than "This " and " a sentence". Note the subtle spaces at the end of "This" and beginning of "a sentence". Again, this answer is probably what the questioner actually wants, but it's not what he asked and, I repeat, String.Split won't trivially solve it.
@IRBMe have you read the question? 'I want to split on "is". So I will get "This " and " a sentence"'. See the spaces in the results??? This is exacly what Split does.
|
55

You can use the Regex.Split method, something like this:

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 satisfies the example you gave. Note that an ordinary String.Split will also split on the "is" at the end of the word "This", hence why I used the Regex method and included the word boundaries around the "is". Note, however, that if you just wrote this example in error, then String.Split will probably suffice.

5 Comments

@ EDIT: I wasn't sure either, but you can still use the normal string split and just pad spaces on either side if his goal is to ONLY remove the word "is".
That doesn't work either (at least not without a lot more effort), because you don't know whether the space should go on the left, the right or both without knowing the positions of the word that was split on in the string.
Seems overly complicated as String.Splity allows you to split on a string already...
I've already addressed this in my edit to my answer, in the comment above and in 3 comments on another answer. String.Split does not work for the example provided in the question. I'm not going to repeat myself yet again by explaining why. You can read all of the other comments if you wish to know.
note that the regex split method doesn't remove of pre delimiter and trailing delimiter on the variable... :(
37

Based on existing responses on this post, this simplify the implementation :)

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);
        }


    }
}

Comments

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

for(int i=0; i<res.length; i++)
    Console.Write(res[i]);

EDIT: The "is" is padded on both sides with spaces in the array in order to preserve the fact that you only want the word "is" removed from the sentence and the word "this" to remain intact.

1 Comment

Except that's not what they wanted. They clearly included trailing and leading spaces in the desired output of the remainder/split values.
8

...In short:

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

Comments

6

Or use this code; ( same : new String[] )

.Split(new[] { "Test Test" }, StringSplitOptions.None)

Comments

5

You can use String.Replace() to replace your desired split string with a character that does not occur in the string and then use String.Split on that character to split the resultant string for the same effect.

Comments

2

Here is an extension function to do the split with a string separator:

public static string[] Split(this string value, string seperator)
{
    return value.Split(new string[] { seperator }, StringSplitOptions.None);
}

Example of usage:

string mystring = "one[split on me]two[split on me]three[split on me]four";
var splitStrings = mystring.Split("[split on me]");

1 Comment

This is identical to the answer posted seven years prior.
0
var dict = File.ReadLines("test.txt")
               .Where(line => !string.IsNullOrWhitespace(line))
               .Select(line => line.Split(new char[] { '=' }, 2, 0))
               .ToDictionary(parts => parts[0], parts => parts[1]);


or 

    enter code here

line="[email protected][email protected]";
string[] tokens = line.Split(new char[] { '=' }, 2, 0);

ans:
tokens[0]=to
token[1][email protected][email protected]

Comments

0

You can do something like this:

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

But usually that is not the case, we should have splitter and loop through them:

string phrase = "This is a sentence";
string[] words = phrase.Split(' ');

foreach (var word in words)
{
    System.Console.WriteLine($"<{word}>");
}

For more info, visit Microsoft website about String.Split

https://learn.microsoft.com/en-us/dotnet/csharp/how-to/parse-strings-using-split

Comments

-1
namespace MyNamespace
{
    public static class StringHelper
    {
        public static string[] Split(this string input, string sup, StringSplitOptions options = StringSplitOptions.None)
        {
            if (input.Contains(sup))
            {
                return input.Split(new[] { sup }, options);
            }
            return new string[] { input };
        }
    }
}

Example Usage:

using System;

namespace MyNamespace
{
    class Program
    {
        static void Main()
        {
            string example = "Hello, how are you?";
            string[] result = example.Split("how");
            
            foreach (var str in result)
            {
                Console.WriteLine(str);
            }
        }
    }
}

In this example, the string "Hello, how are you?" is split by the substring "how", resulting in an array with two elements: "Hello, " and " are you?".

2 Comments

This would be identical to the answer posted thirteen years prior, except that it's worse because it includes an unnecessary call to Contains. Split already returns an array with the full original string as its first element if the separator is not found.
@GSerg Well, there is no StringSplitOptions in the original answer. Also, the basis for splitting a string is that sometimes there is no delimiter in the input and it is better to return the original string.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.