C#获取字符串字符的位数(区分中文和英文长度)

大家可以先看一下编码表,注意如果不在编码表内的字符则视为63Ascii编码表

请看以下代码

private static int GetStrLength(string str)
        {
            if (string.IsNullOrEmpty(str)) 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;
                }
            }
            Console.WriteLine("当前字符串长度为:" + tempLen);
            return tempLen;
        }
posted @ 2021-06-05 11:12  yassine  阅读(316)  评论(0编辑  收藏  举报