I have this string:
My name is Marco and I'm from Italy
I'd like to split it, with delimiter is Marco and
, so I should get an array with
My name
at [0] andI'm from Italy
at [1].How can I do it with C#?
I tried with:
.Split("is Marco and")
But it wants only a single char.
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);
}
}
}
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");
There is a version of string.Split
that takes an array of strings and a StringSplitOptions
parameter:
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);
.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...
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);
Source: Stackoverflow.com