c#替换空格 空白 replace

//过滤空白字符,替换无效路径文件名
public static string Escape(string id)
{
    if (string.IsNullOrEmpty(id)) return string.Empty;
    var invalidChars = Path.GetInvalidFileNameChars().Concat(Path.GetInvalidPathChars()).ToHashSet();
    return new string(id.Select(c => invalidChars.Contains(c) ? '_' : c).Where(c => !char.IsWhiteSpace(c)).ToArray());
}

    public static string Escape(this string id)
    {
        if (string.IsNullOrEmpty(id)) return string.Empty;
        char[] chars ={
            (char) 0x00, (char) 0x01, (char) 0x02, (char) 0x03, (char) 0x04, (char) 0x05,
            (char) 0x06, (char) 0x07, (char) 0x08, (char) 0x09, (char) 0x0a, (char) 0x0b,
            (char) 0x0c, (char) 0x0d, (char) 0x0e, (char) 0x0f, 
            (char) 0x10, (char) 0x11, (char) 0x12, (char) 0x13, (char) 0x14, (char) 0x15,
            (char) 0x16, (char) 0x17, (char) 0x18, (char) 0x19, (char) 0x1a, (char) 0x1b, 
            (char) 0x1c, (char) 0x1d, (char) 0x1e, (char) 0x1f,
            (char) 0x20, (char) 0x85, (char) 0xc2, (char) 0xa0, (char) 0x7f,
            (char) 0x2000, (char) 0x2001, (char) 0x2002, (char) 0x2003, (char) 0x2004, (char) 0x2005,
            (char) 0x2006, (char) 0x2007, (char) 0x2008, (char) 0x2009, (char) 0x200a, 
            (char) 0x2028, (char) 0x2029, (char) 0x205f, (char) 0x3000
        };
        return new string(id.Where(c => !chars.Contains(c)));
    }
    public static string Escape2(this string id)
    {
        if (string.IsNullOrEmpty(id)) return string.Empty;
        return new string(id.Where(c=>!char.IsWhiteSpace(c)).ToArray());
    }
        //无效路径和无效文件名和空白替换成_
        public static string Escape(string id)
        {
            return string.IsNullOrEmpty(id) ? string.Empty : new string(id.Select(c => Path.GetInvalidFileNameChars().Concat(Path.GetInvalidPathChars()).Contains(c) || char.IsWhiteSpace(c) ? '_' : c).ToArray());
        }
        //过滤无效路径和无效文件名
        public static string Escape(string id)
        {
            if (string.IsNullOrEmpty(id)) return string.Empty;
            var invalidChars = Path.GetInvalidFileNameChars().Concat(Path.GetInvalidPathChars()).ToHashSet();
            return new string(id.Where(c => !invalidChars.Contains(c) && !char.IsWhiteSpace(c)).ToArray());
        }
posted @ 2020-12-04 13:59  月渊  阅读(1062)  评论(0编辑  收藏  举报