C# Remove special characters

后端 未结 7 2326
孤街浪徒
孤街浪徒 2021-02-07 08:08

I want to remove all special characters from a string. Allowed characters are A-Z (uppercase or lowercase), numbers (0-9), underscore (_), white space ( ), pecentage(%) or the d

7条回答
  •  清酒与你
    2021-02-07 08:41

    You can simplify the first method to

    StringBuilder sb = new StringBuilder();
    foreach (char c in input)
    {
        if (Char.IsLetterOrDigit(c) || c == '.' || c == '_' || c == ' ' || c == '%')
        { sb.Append(c); }
    }
    return sb.ToString();
    

    which seems to pass simple tests. You can shorten it using LINQ

    return new string(
        input.Where(
            c => Char.IsLetterOrDigit(c) || 
                c == '.' || c == '_' || c == ' ' || c == '%')
        .ToArray());
    

提交回复
热议问题