Search code examples
vb.netstringsplitlimit

How to split a string into N parts?


I'm trying to split a string into only two parts where the delimiter character can occur multiple times.

The code below doesn't work as I'm not allowed to specify a limit option:

Dim output = input.Split("=", 1)

Any ideas?


Solution

  • You can use the String.Split(Char[], Int32, StringSplitOptions) overload.

    Notice that the first parameter is a Char array, not a single character. The second parameter enables you to specify the maximum number of substrings to return.

    VB.NET

    Option Strict On
    

    Important: You should always have the strict compiler option set to On.

    Dim input As String = "aaaa=bbbb=cccc=dddd"
    Dim separators As Char() = { "="c }
    Dim count As Integer = 2
    Dim options As StringSplitOptions = StringSplitOptions.RemoveEmptyEntries
    Dim output As String() = input.Split(separators, count, options)
    
    For Each part As String In output
        Console.WriteLine(part)
    Next
    

    C#

    string input = "aaaa=bbbb=cccc=dddd";
    char[] separators = new[] { '=' };
    int count = 2;
    StringSplitOptions options = StringSplitOptions.RemoveEmptyEntries;
    string[] output = input.Split(separators, count, options);
    
    foreach (string part in output)
    {
        Console.WriteLine(part);
    }
    

    This will return an array containing two elements:

    aaaa
    bbbb=cccc=dddd