How can I split a string with a string delimiter? [duplicate]
Andrew Mclaughlin
I have this string:
My name is Marco and I'm from ItalyI'd like to split it, with delimiter is Marco and, so I should get an array with
My nameat [0] andI'm from Italyat [1].
How can I do it with C#?
I tried with:
.Split("is Marco and")But it wants only a single char.
17 Answers
string[] tokens = str.Split(new[] { "is Marco and" }, StringSplitOptions.None);If you have a single character delimiter (like for instance ,), you can reduce that to (note the single quotes):
string[] tokens = str.Split(','); 8 .Split(new string[] { "is Marco and" }, StringSplitOptions.None)Consider the spaces surronding "is Marco and". Do you want to include the spaces in your result, or do you want them removed? It's quite possible that you want to use " is Marco and " as separator...
You are splitting a string on a fairly complex sub string. I'd use regular expressions instead of String.Split. The later is more for tokenizing you text.
For example:
var rx = new System.Text.RegularExpressions.Regex("is Marco and");
var array = rx.Split("My name is Marco and I'm from Italy"); Try this function instead.
string source = "My name is Marco and I'm from Italy";
string[] stringSeparators = new string[] {"is Marco and"};
var result = source.Split(stringSeparators, StringSplitOptions.None); You could use the IndexOf method to get a location of the string, and split it using that position, and the length of the search string.
You can also use regular expression. A simple google search turned out with this
using System;
using System.Text.RegularExpressions;
class Program { static void Main() { string value = "cat\r\ndog\r\nanimal\r\nperson"; // Split the string on line breaks. // ... The return value from Split is a string[] array. string[] lines = Regex.Split(value, "\r\n"); foreach (string line in lines) { Console.WriteLine(line); } }
} Read C# Split String Examples - Dot Net Pearls and the solution can be something like:
var results = yourString.Split(new string[] { "is Marco and" }, StringSplitOptions.None); There is a version of string.Split that takes an array of strings and a StringSplitOptions parameter: