正常情況下,我們是直接去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;