[c#] 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#?

This question is related to c# .net string

The answer is


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


    }
}

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

...In short:

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

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]

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.


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.


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.


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

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

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

Examples related to c#

How can I convert this one line of ActionScript to C#? Microsoft Advertising SDK doesn't deliverer ads How to use a global array in C#? How to correctly write async method? C# - insert values from file into two arrays Uploading into folder in FTP? Are these methods thread safe? dotnet ef not found in .NET Core 3 HTTP Error 500.30 - ANCM In-Process Start Failure Best way to "push" into C# array

Examples related to .net

You must add a reference to assembly 'netstandard, Version=2.0.0.0 How to use Bootstrap 4 in ASP.NET Core No authenticationScheme was specified, and there was no DefaultChallengeScheme found with default authentification and custom authorization .net Core 2.0 - Package was restored using .NetFramework 4.6.1 instead of target framework .netCore 2.0. The package may not be fully compatible Update .NET web service to use TLS 1.2 EF Core add-migration Build Failed What is the difference between .NET Core and .NET Standard Class Library project types? Visual Studio 2017 - Could not load file or assembly 'System.Runtime, Version=4.1.0.0' or one of its dependencies Nuget connection attempt failed "Unable to load the service index for source" Token based authentication in Web API without any user interface

Examples related to string

How to split a string in two and store it in a field String method cannot be found in a main class method Kotlin - How to correctly concatenate a String Replacing a character from a certain index Remove quotes from String in Python Detect whether a Python string is a number or a letter How does String substring work in Swift How does String.Index work in Swift swift 3.0 Data to String? How to parse JSON string in Typescript