去掉全角空格

有时候复制网上的代码会出现编译不通过的问题,报类似这样的一个问题:error: stray '\161' in program。在网上查了一下,就是全角空格的问题。借助于网上的一段Java代码,把它转换成了C#的代码,并制作了一个小工具,用于去除全角空格。原理是从文字的字节码中将全角空格的字节码(161)替换为半角空格的字节码(32):

主要代码:

 public static string FullWidthToHalfWidth(string str)
        {
            byte[] t = Encoding.Default.GetBytes(str);
            for (int i = 0; i < t.Length; i++)
            {
                if ((t[i].ToString() == "161") && (t[i + 1].ToString() == "161"))
                {
                    t[i] = 32;
                    if (i + 1 == t.Length - 1)
                    {
                        t[i + 1] = 0;
                    }
                    else
                    {
                        for (int j = i + 1; j + 1 < t.Length; j++)
                        {
                            t[j] = t[j + 1];
                            if (j + 1 == t.Length - 1)
                            {
                                t[j + 1] = 0;
                            }
                        }
                    }
                }
            }
            return Encoding.Default.GetString(t);
        }

源文件下载

原文地址:https://www.cnblogs.com/liszt/p/2004253.html