Question

Unfortunately, there seems to be no string.Split(string separator), only string.Split(char speparator).

I want to break up my string based on a multi-character separator, a la VB6. Is there an easy (that is, not by referencing Microsoft.VisualBasic or having to learn RegExes) way to do this in c#?

EDIT: Using .NET Framework 3.5.

Was it helpful?

Solution

String.Split() has other overloads. Some of them take string[] arguments.

string original = "first;&second;&third";
string[] splitResults = original.Split( new string[] { ";&" }, StringSplitOptions.None );

OTHER TIPS

the regex for spliting string is extremely simple so i would go with that route.

http://msdn.microsoft.com/en-us/library/8yttk7sy.aspx

Which version of .Net? At least 2.0 onwards includes the following overloads:

.Split(string[] separator, StringSplitOptions options)  
.Split(string[] separator, int count, StringSplitOptions options)

Now if they'd only fix it to accept any IEnumerable<string> instead of just array.

The regex version is probably prettier but this works too:

string[] y = { "bar" };

string x = "foobarfoo";
foreach (string s in x.Split(y, StringSplitOptions.None))
      Console.WriteLine(s);

This'll print foo twice.

 string[] stringSeparators = new string[] {"[stop]"};
    string[] result;
result = someString.Split(stringSeparators, StringSplitOptions.None);

via http://msdn.microsoft.com/en-us/library/tabh47cf.aspx

I use this under .NET 2.0 all the time.

string[] args = "first;&second;&third".Split(";&".ToCharArray(),StringSplitOptions.RemoveEmptyEntries);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top