C#获取带汉字的字符串长度

正常情况下,我们是直接去string的length的,但是汉字是有两个字节的,所以直接用length是错的。如下图:

 

所以应该用以下代码来获取长度:

private void button1_Click(object sender, EventArgs e)
        {
            string s = textBox1.Text;
            int i = GetLength(s);
            MessageBox.Show(i.ToString());
        }

        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;
        }

运行结果如下图:

 

也可以用这个获取长度:

int i = System.Text.Encoding.Default.GetBytes(s).Length;

 

posted @ 2016-08-31 13:46  涂山吕吕  阅读(12498)  评论(1编辑  收藏  举报