C# 汉字的字符串截取指定字节的长度

时间:2023-01-12 15:58:49

   int index = 0;
            int setCharCount = 74;
            string str1 = "三星 SCH-I829 电信3G手机(优雅白)CDMA2000/GSM 双模双待双通";
            byte[] bt = new ASCIIEncoding().GetBytes(str1);
            if (bt.Length > setCharCount)//当超过需要的字节时
            {
                Array.Resize(ref bt, setCharCount);//获取需要长度的字节
                for (int i = 0; i < bt.Length; i++)
                    if (bt[i] == 63)index++; //计算汉字数  
                str1.Substring(0, index + (setCharCount - index*2)); //截取所需长度的字符串
            }