不知道大家注意没,用c#下自带的str.Length方法获得字符串str长度的时候,返回的总是字符的个数,但是如果字符串中包含汉字的话,一个汉字是占两个字符长度的,获取的长度值就有了问题。
解决方案:
原文: http://www.cnblogs.com/haibing0107/p/5825600.html
正常情况下,我们是直接去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;