Can I split a string in c# VB6-style without referencing Microsoft.VisualBasic?
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.
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.
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);
I use this under .NET 2.0 all the time.
string[] args = "first;&second;&third".Split(";&".ToCharArray(),StringSplitOptions.RemoveEmptyEntries);