导航

检测含有中文字符串的实际长度

Posted on 2010-07-03 10:43  ykhi  阅读(321)  评论(0)    收藏  举报

            string MyString = "中华人民共和国中央人民政府主席,1950年。";
            ASCIIEncoding MyData = new ASCIIEncoding();
            byte[] MyBytes = MyData.GetBytes(MyString);
            //MyLength 为字符串的实际长度
            int MyLength= 0; 
            for (int i = 0; i <= MyBytes.Length - 1; i++)
            {
                //判断是否为汉字或全脚符号
                if (MyBytes[i] == 63) 
                {
                    MyLength++;
                }
                MyLength++;
            }
            String MyInfo ="“"+MyString+ "”共有"+MyString.Length.ToString()+"个字符,";
            MyInfo += "实际长度为" + MyLength.ToString() + "字节。";
            MessageBox.Show(MyInfo, "信息提示", MessageBoxButtons.OK, MessageBoxIcon.Information);