正常情况下,我们是直接去string的length的,但是汉字是有两个字节的,所以直接用length是错的。如下图:
所以应该用以下代码来获取长度:
?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 | 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; } |
运行结果如下图:
也可以用这个获取长度:
?
1 | int i = System.Text.Encoding.Default.GetBytes(s).Length; |
通过系统提供函数我们就可以获取中文的真实长度,是不是很简单
原文链接:http://www.cnblogs.com/haibing0107/p/5825600.html