首页 新闻 赞助 找找看

中文转byte判断指定byte位是否为中文的一半

0
悬赏园豆:60 [已解决问题] 解决于 2014-10-13 20:45

有一个gb2312的字符串,里面有中文有英文,我要每次截取10个字节或者11个字节。取决于第十个字节是否是汉字的一半。有没有什么办法可以判断第十个字节加第十一个字节是一个汉字。当然也有可能第九个字节和第十个字节为一个汉字。

路飞的小蝴蝶的主页 路飞的小蝴蝶 | 初学一级 | 园豆:46
提问于:2014-10-10 19:58
< >
分享
最佳答案
0

按照你的说明是没办法。GB2312里的高字节和低字节的取值范围几乎完全一样,所以没办法来判断。如果是UTF-8则可以。

但是你可以通过对10个字节数据进行整体判断:比如小于128的字节数量,偶数说明第十个字节是汉字的低字节,基数则是高字节。

收获园豆:60
519740105 | 大侠五级 |园豆:5810 | 2014-10-10 22:31
其他回答(5)
0

先取长度为10的字符串,从5开始,判断其字节数是否小于10[小于等于9],小于10时长度加1,再判断其字节数,等于10时,取10个,等于11时[是汉字],取11

大志若愚 | 园豆:2138 (老鸟四级) | 2014-10-11 10:00
0

先判断字符数和字节数做对比验证就知道了

draculav | 园豆:734 (小虾三级) | 2014-10-11 10:06
0

如果性能可以承受的话,先转换成string,再截取:

private static byte[] Substring(byte[] text, Encoding encoding, int start, int len)
{
      return encoding.GetBytes(encoding.GetString(text).Substring(start, len));
}

sweetjian | 园豆:276 (菜鸟二级) | 2014-10-11 12:32

上面的答案,我好像理解错误了,参考这个:

        private static byte[] Substring(byte[] text, int byteCount = 10)
        {
            for (int i = 0; i < text.Length; /*NONE*/)
            {
                if (text[i] > 127)
                {
                    i += 2;//非ASCII码,占用2个字节
                }
                else
                {
                    i++;//ASCII码,占用1个字节
                }
                if (i >= byteCount)
                {
                    byte[] result = new byte[i];
                    Buffer.BlockCopy(text, 0, result, 0, result.Length);
                    return result;
                }
            }
            return new byte[0];
        }

 

支持(0) 反对(0) sweetjian | 园豆:276 (菜鸟二级) | 2014-10-11 13:11
0
        /// <summary>
        /// 计算字符串长度,全角算两个,半角算一个
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static int GetLength(string str)
        {
            if (str.Length == 0) return 0;
            ASCIIEncoding ascii = new ASCIIEncoding();
            int tempLen = 0; byte[] s = ascii.GetBytes(str);
            for (int i = 0; i < s.Length; i++)
            {
                if ((int)s[i] == 63)
                {
                    tempLen += 2;
                }
                else
                {
                    tempLen += 1;
                }
            }
            return tempLen;
        }
只会造轮子 | 园豆:2274 (老鸟四级) | 2014-10-11 14:04
0
#powershell代码
#判断每个字符为英文还是中文,测试通过

[string]$a = "a汗dfks真大寺佛js算msk"
$b = $a.tochararray()
foreach ($temp in $b)
{
    $temp2 = $null
    $temp2 = [byte][char]"$temp"
    if ($temp2 -eq $null)
    {
        echo "$temp 是中文,或双字节字符"
    }
    else
    {
        echo "$temp 是英文,或单字节字符"
    }
    

}
PowerShell免费软件 | 园豆:332 (菜鸟二级) | 2014-10-11 21:27
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册