How can you strip non-ASCII characters from a string? (in C#)

前端 未结 11 1337
迷失自我
迷失自我 2020-11-22 17:24

How can you strip non-ASCII characters from a string? (in C#)

11条回答
  •  攒了一身酷
    2020-11-22 17:47

    Inspired by philcruz's Regular Expression solution, I've made a pure LINQ solution

    public static string PureAscii(this string source, char nil = ' ')
    {
        var min = '\u0000';
        var max = '\u007F';
        return source.Select(c => c < min ? nil : c > max ? nil : c).ToText();
    }
    
    public static string ToText(this IEnumerable source)
    {
        var buffer = new StringBuilder();
        foreach (var c in source)
            buffer.Append(c);
        return buffer.ToString();
    }
    

    This is untested code.

提交回复
热议问题