How can I remove quoted string literals from a string in C#?

前端 未结 3 512
遇见更好的自我
遇见更好的自我 2021-01-21 00:28

I have a string:

Hello \"quoted string\" and \'tricky\"stuff\' world

and want to get the string minus the quoted parts back. E.g.,

3条回答
  •  别那么骄傲
    2021-01-21 00:56

    In case, like me, you're afraid of regex, I've put together a functional way to do it, based on your example string. There's probably a way to make the code shorter, but I haven't found it yet.

    private static string RemoveQuotes(IEnumerable input)
    {
        string part = new string(input.TakeWhile(c => c != '"' && c != '\'').ToArray());
        var rest = input.SkipWhile(c => c != '"' && c != '\'');
        if(string.IsNullOrEmpty(new string(rest.ToArray())))
            return part;
        char delim = rest.First();
        var afterIgnore = rest.Skip(1).SkipWhile(c => c != delim).Skip(1);
        StringBuilder full = new StringBuilder(part);
        return full.Append(RemoveQuotes(afterIgnore)).ToString();
    }
    

提交回复
热议问题