zoukankan      html  css  js  c++  java
  • C#怎么判断字符是不是汉字 汉字和Unicode编码互相转换

    判断一个字符是不是汉字通常有三种方法,第1种用 ASCII 码判断(在 ASCII码表中,英文的范围是0-127,而汉字则是大于127,根据这个范围可以判断),第2种用汉字的 UNICODE 编码范围判 断(汉字的 UNICODE 编码范围是4e00-9fbb),第3种用正则表达式判断,下面是具体方法。

    但是实际上并不怎么准确(从业务上讲,比如全角输入的数字),所以后来简单修改了一下 代码

    public static bool IsChinese( this string CString)
    {
        bool BoolValue = false;
        List<string> specialChar = new List<string> { "", "", "", "", "", "", "", "", "", "",
            "", "", "", "", "", "", "", "", "", "",  "", "", "", "", "", "", "", "", "", "" , "", "", "", "", "", "",
            "", "", "", "", "", "", "", "", "", "",  "", "", "", "", "", "", "", "", "", "" , "", "", "", "", "", "",
            "", "", "", "", "", "", "", "", "", "", "_", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", ""  };
        for (int i = 0; i < CString.Length; i++)
        {
            if (Convert.ToInt32(Convert.ToChar(CString.Substring(i, 1))) < Convert.ToInt32(Convert.ToChar(128)))
            {
                BoolValue = false;
            }
            else
            {
                BoolValue = true;
            }
        }
        if (BoolValue) {
            if (specialChar.Any(x => CString.Contains(x))) {
                BoolValue = false;
            }
        }
        return BoolValue;
    }

    当然还有一些特殊字符 也能通过,比如全角输入的π,Ω

    public static string String2Unicode(string source)
    {
        byte[] bytes = Encoding.Unicode.GetBytes(source);
        StringBuilder stringBuilder = new StringBuilder();
        for (int i = 0; i < bytes.Length; i += 2)
        {
            stringBuilder.AppendFormat("\u{0}{1}", bytes[i + 1].ToString("x").PadLeft(2, '0'), bytes[i].ToString("x").PadLeft(2, '0'));
        }
        return stringBuilder.ToString();
    }
     
    
    public static string Unicode2String(string source)
    {
        return new Regex(@"\u([0-9A-F]{4})", RegexOptions.IgnoreCase | RegexOptions.Compiled).Replace(
                     source, x => string.Empty + Convert.ToChar(Convert.ToUInt16(x.Result("$1"), 16)));
    }
  • 相关阅读:
    cmanformat
    mysql-sql语言参考
    jQuery 判断多个 input checkbox 中至少有一个勾选
    Java实现 蓝桥杯 算法提高 计算行列式
    Java实现 蓝桥杯 数独游戏
    Java实现 蓝桥杯 数独游戏
    Java实现 蓝桥杯 数独游戏
    Java实现 蓝桥杯 算法提高 成绩排序2
    Java实现 蓝桥杯 算法提高 成绩排序2
    Java实现 蓝桥杯 算法提高 成绩排序2
  • 原文地址:https://www.cnblogs.com/majiang/p/11504727.html
Copyright © 2011-2022 走看看