超简单C#获取带汉字的字符串真实长度(单个英文长度为1,单个中文
发布时间:2020-12-15 05:43:55 所属栏目:百科 来源:网络整理
导读:正常情况下,我们是直接去string的length的,但是汉字是有两个字节的,所以直接用length是错的。如下图: 所以应该用以下代码来获取长度: private void button1_Click(object sender,EventArgs e) { string s = textBox1.Text; int i = GetLength(s); Messa
正常情况下,我们是直接去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; 通过系统提供函数我们就可以获取中文的真实长度,是不是很简单 您可能感兴趣的文章:
(编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |