首页 > 编程 > C# > 正文

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

2019-10-29 21:03:09
字体:
来源:转载
供稿:网友

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

C#,汉字,字符串,长度

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

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#,汉字,字符串,长度

也可以用这个获取长度:

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

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


注:相关教程知识阅读请移步到c#教程频道。
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表