0

I want to split a string at multiple delimeters and would want to get the delimeters in the output. For example, if the input string is Hello World and my delimeters are 'l','o', the output array of strings should be "He", "l", "l", "o", " W","o","r","l","d".Is there a built in function for that? String.Split does not have such an option. I remember, StringTokenizer in java had this option. Please advice.

Victor Mukherjee
  • 10,487
  • 16
  • 54
  • 97

2 Answers2

0

You can use Regexp.Split for it. For example:

  Dim input As String = "Hello World"    
  Dim pattern As String = "(l)|(o)" 
  For Each result As String In Regex.Split(input, pattern) 
     Console.WriteLine("'{0}'", result)
  Next

For more information about Regex.Split, please visit http://msdn.microsoft.com/en-us/library/8yttk7sy.aspx

Sargis Koshkaryan
  • 1,012
  • 3
  • 9
  • 19
0

These extension methods works:

public static class SplitEx
{
    public static string[] SplitInline(this string text, char delimeter)
    {
        var results = text.Split(delimeter);
        return
            results
                .Take(1)
                .Concat(
                    results
                        .Skip(1)
                        .SelectMany(x => new []
                        {
                            Convert.ToString(delimeter),
                            x,
                        }))
                .Where(x => !String.IsNullOrWhiteSpace(x))
                .ToArray();
    }

    public static string[] SplitInline(this string text, string delimeters)
    {
        if (String.IsNullOrEmpty(delimeters))
        {
            return new [] { text };
        }
        else
        {
            var head = delimeters[0];
            var tail = new string(delimeters.Skip(1).ToArray());
            return
                text
                    .SplitInline(head)
                    .SelectMany(x => x.SplitInline(tail))
                    .ToArray();
        }
    }
}

It can be used like this:

var text = "Hello World";

var result = text.SplitInline("lo");

I get the following result:

result

Enigmativity
  • 113,464
  • 11
  • 89
  • 172