正常情況下,我們是直接去string的length的,但是漢字是有兩個字節(jié)的,所以直接用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; |
通過系統(tǒng)提供函數(shù)我們就可以獲取中文的真實長度,是不是很簡單
原文鏈接:http://www.cnblogs.com/haibing0107/p/5825600.html