C# Extension Method - String Split that also accepts an Escape Character

后端 未结 10 1700
我在风中等你
我在风中等你 2020-12-17 00:19

I\'d like to write an extension method for the .NET String class. I\'d like it to be a special varation on the Split method - one that takes an escape character to prevent s

10条回答
  •  攒了一身酷
    2020-12-17 00:31

    How about:

    public static IEnumerable Split(this string input, 
                                            string separator,
                                            char escapeCharacter)
    {
        int startOfSegment = 0;
        int index = 0;
        while (index < input.Length)
        {
            index = input.IndexOf(separator, index);
            if (index > 0 && input[index-1] == escapeCharacter)
            {
                index += separator.Length;
                continue;
            }
            if (index == -1)
            {
                break;
            }
            yield return input.Substring(startOfSegment, index-startOfSegment);
            index += separator.Length;
            startOfSegment = index;
        }
        yield return input.Substring(startOfSegment);
    }
    

    That seems to work (with a few quick test strings), but it doesn't remove the escape character - that will depend on your exact situation, I suspect.

提交回复
热议问题