hbrock hbrock - 4 months ago 11
C# Question

Split a string on multiple delimiters and keep them in the output

I have an string that can be 2 to N chars long. I also have 4 ocode (each 2 chars long).

Is there a way to so something like:

var tmpArray = inputStr.Split(char1, char2, char3, char4).ToArray();


Say that the opcodes are A,B,C,D or 8 and I have this string AB123456789C123412341234B123 the array would be like this:


A

B

123456789

C

123412341234

B

123

Answer

Try this,

private char[] alphabets = {'A','B','C', 'D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'};    

var input = "AB123456789C123412341234B123";
var result = input.SplitAndKeep(alphabets).ToList();

enter image description here

public static class Extensions
{
    public static IEnumerable<string> SplitAndKeep(this string s, char[] delims)
    {
        int start = 0, index;
        while ((index = s.IndexOfAny(delims, start)) != -1)
        {
            if (index - start > 0)
                yield return s.Substring(start, index - start);
            yield return s.Substring(index, 1);
            start = index + 1;
        }
        if (start < s.Length)
        {
            yield return s.Substring(start);
        }
    }
}