Wednesday, February 9, 2011

Can I split a string in c# VB6-style without referencing Microsoft.VisualBasic?

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.

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

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

    From ooo
  • 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.

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

    string original = "first;&second;&third";
    string[] splitResults = original.Split( new string[] { ";&" }, StringSplitOptions.None );
    
  • You could simply use String.Split. It is part of the base library and there are many overloads that are much like VB.

  • 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.

    From Dana
  •  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);
    
    From J.Hendrix

0 comments:

Post a Comment