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

后端 未结 10 1705
我在风中等你
我在风中等你 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:50

    public static string[] Split(this string input, string separator, char escapeCharacter)
    {
        Guid g = Guid.NewGuid();
        input = input.Replace(escapeCharacter.ToString() + separator, g.ToString());
        string[] result = input.Split(new string []{separator}, StringSplitOptions.None);
        for (int i = 0; i < result.Length; i++)
        {
            result[i] = result[i].Replace(g.ToString(), escapeCharacter.ToString() + separator);
        }
    
        return result;
    }
    

    Probably not the best way of doing it, but it's another alternative. Basically, everywhere the sequence of escape+seperator is found, replace it with a GUID (you can use any other random crap in here, doesn't matter). Then use the built in split function. Then replace the guid in each element of the array with the escape+seperator.

提交回复
热议问题