views:

975

answers:

7

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.

+1  A: 

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

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

ooo
+1  A: 

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.

Joel Coehoorn
+7  A: 

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

string original = "first;&second;&third";
string[] splitResults = original.Split( new string[] { ";&" }, StringSplitOptions.None );
Joel B Fant
+3  A: 

You could simply use String.Split. It is part of the base library and there are many overloads that are much like VB.

Dave Ganger
A: 

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.

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

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

A: 

I use this under .NET 2.0 all the time.

string[] args = "first;&second;&third".Split(";&".ToCharArray(),StringSplitOptions.RemoveEmptyEntries);
J.Hendrix