Saobi
Saobi

Reputation: 17011

How do I split a string by a multi-character delimiter in C#?

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#?

Upvotes: 247

Views: 280204

Answers (12)

NoobInCoding
NoobInCoding

Reputation: 21

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?".

Upvotes: -1

Alireza
Alireza

Reputation: 104650

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

Upvotes: 0

SteveD
SteveD

Reputation: 867

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]");

Upvotes: 3

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

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

Upvotes: 6

Prabu
Prabu

Reputation: 41

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]

Upvotes: 0

ParPar
ParPar

Reputation: 7549

...In short:

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

Upvotes: 8

eka808
eka808

Reputation: 2317

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


    }
}

Upvotes: 37

Susmeet Khaire
Susmeet Khaire

Reputation: 1

string strData = "This is much easier"
int intDelimiterIndx = strData.IndexOf("is");
int intDelimiterLength = "is".Length;
str1 = strData.Substring(0, intDelimiterIndx);
str2 = strData.Substring(intDelimiterIndx + intDelimiterLength, strData.Length - (intDelimiterIndx + intDelimiterLength));

Upvotes: -6

ahawker
ahawker

Reputation: 3364

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.

Upvotes: 30

IRBMe
IRBMe

Reputation: 4425

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.

Upvotes: 56

Paul Sonier
Paul Sonier

Reputation: 39480

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.

Upvotes: 5

bruno conde
bruno conde

Reputation: 48265

http://msdn.microsoft.com/en-us/library/system.string.split.aspx

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

Upvotes: 297

Related Questions