正常情況下,我們是直接去string的length的,但是漢字是有兩個(gè)字節(jié)的,所以直接用length是錯(cuò)的。如下圖:
所以應(yīng)該用以下代碼來獲取長(zhǎng)度:
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; }
運(yùn)行結(jié)果如下圖:
也可以用這個(gè)獲取長(zhǎng)度:
int i = System.Text.Encoding.Default.GetBytes(s).Length;
通過系統(tǒng)提供函數(shù)我們就可以獲取中文的真實(shí)長(zhǎng)度,是不是很簡(jiǎn)單
新聞熱點(diǎn)
疑難解答
圖片精選
網(wǎng)友關(guān)注