Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how do you split a string with a string in C#

I would like to split a string into a String[] using a String as a delimiter.

String delimit = "[break]";
String[] tokens = myString.Split(delimit);

But the method above only works with a char as a delimiter.

Any takers?

like image 699
Kieran Avatar asked Feb 10 '10 04:02

Kieran


People also ask

Can strings be split?

The split() method splits a string into an array of substrings. The split() method returns the new array. The split() method does not change the original string. If (" ") is used as separator, the string is split between words.

How do I split a line in a string?

The splitlines() method splits a string into a list. The splitting is done at line breaks.

How do you split a string into characters?

(which means "any character" in regex), use either backslash \ to escape the individual special character like so split("\\.") , or use character class [] to represent literal character(s) like so split("[.]") , or use Pattern#quote() to escape the entire string like so split(Pattern.


2 Answers

Like this:

mystring.Split(new string[] { delimit }, StringSplitOptions.None);

For some reason, the only overloads of Split that take a string take it as an array, along with a StringSplitOptions.
I have no idea why there isn't a string.Split(params string[]) overload.

like image 163
SLaks Avatar answered Oct 24 '22 19:10

SLaks


I personally prefer to use something like this, since regex has that split:

public static string[] Split(this string input, string delimit)
{
  return Regex.Split(input, delimit);
}
like image 32
Victor Avatar answered Oct 24 '22 19:10

Victor