技术思绪摘录旅行笔记
根据维基百科描述,Zero-width Spaces大致的作用是宽度为0,但实际存在的字符,多数作用于排班,非打印字符,就是看不见的字符,当这种字符出现在代码中,多多少少会带来一些麻烦,比如出现在URL中,出现在关键字符串中,本文给大家详细介绍一下,再说下C#中如何处理和去掉这种字符。

维基百科:Zero-width_space

国外网友介绍:Zero-width Spaces

The zero-width space, abbreviated ZWSP, is a non-printing character used in computerized typesetting to indicate word boundaries to text processing systems when using scripts that do not use explicit spacing, or after characters (such as the slash) that are not followed by a visible space but after which there may nevertheless be a line break. It is also used with languages without visible space between words, for example Japanese. Normally, it is not a visible separation, but it may expand in passages that are fully justified.


一般遇到的问题

1、如果出现在URL中

那么一旦斜杠左右有这个字符的时候,你的URL将失去路由的作用,实际上它可能是这样的

看上去是这样:https://www.yangshaofeng.com/ord/info 
实际上是这样:https://www.yangshaofeng.com  /ord /info

那么你请求的时候就是404的错误

2、当出现在关键字符串中

还是因为看不到,所以你的IDE和打印,都显示正常

string str1="张三";
string str2="张三";
if(str1==str2){

}

以上代码会不相等,我一开始遇到的时候,第一感觉是字符编码问题,没想到有一个多了字符。

各种编码切换,都没有解决,依然是false


结合各种文献文档,最终发现:

不可见字符包含了Unicode

​ (Space)

‌ (Non-Joiner)

‍ (Joiner)

 (No-Break Space)


以下给出C#去掉这些不可见字符的代码:

        public static string DeleteUnVisibleChar(string sourceString)
        {
            System.Text.StringBuilder sBuilder = new System.Text.StringBuilder();
            for (int i = 0; i < sourceString.Length; i++)
            {
                int Unicode = sourceString[i];
                if (Unicode >= 16 
                            &&Unicode != 8203
                            && Unicode != 8204
                            && Unicode != 8205
                            && Unicode != 8206
                            && Unicode != 8207
                            && Unicode != 65279)
                {
                    sBuilder.Append(sourceString[i].ToString());
                }
            }
            return sBuilder.ToString();
        }


CarsonIT 微信扫码关注公众号 策略、创意、技术

留下您的脚步

 

最近评论

查看更多>>

站点统计

总文章数:275 总分类数:18 总评论数:88 总浏览数:124.96万

精选推荐

阅读排行

友情打赏

请打开您的微信,扫一扫