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

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

    Here is solution if you want to remove the escape character.

    public static IEnumerable Split(this string input, 
                                            string separator, 
                                            char escapeCharacter) {
        string[] splitted = input.Split(new[] { separator });
        StringBuilder sb = null;
    
        foreach (string subString in splitted) {
            if (subString.EndsWith(escapeCharacter.ToString())) {
                if (sb == null)
                    sb = new StringBuilder();
                sb.Append(subString, 0, subString.Length - 1);
            } else {
                if (sb == null)
                    yield return subString;
                else {
                    sb.Append(subString);
                    yield return sb.ToString();
                    sb = null;
                }
            }
        }
        if (sb != null)
            yield return sb.ToString();
    }
    

提交回复
热议问题