软件编程
位置:首页>> 软件编程>> C#编程>> 超简单C#获取带汉字的字符串真实长度(单个英文长度为1,单个中文长度为2)

超简单C#获取带汉字的字符串真实长度(单个英文长度为1,单个中文长度为2)

作者:wdc  发布时间:2021-11-13 20:37:55 

标签:C#字符串

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

超简单C#获取带汉字的字符串真实长度(单个英文长度为1,单个中文长度为2)

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


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

运行结果如下图:

超简单C#获取带汉字的字符串真实长度(单个英文长度为1,单个中文长度为2)

也可以用这个获取长度:


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

通过系统提供函数我们就可以获取中文的真实长度,是不是很简单

来源:http://www.cnblogs.com/haibing0107/p/5825600.html

0
投稿

猜你喜欢

手机版 软件编程 asp之家 www.aspxhome.com