java中:
1字符=2字節,1字節=8位
英文和數字佔一個字節,中文佔一個字符,也就是兩個字節
在計算的字符串長度的時候,若有漢字,直接用String.length()方法是沒法計算出準確的長度,如:
public static void main(String[] args) {
String userName = "大中國zxc";
int length = userName.length();
//int length = length(userName);
System.out.println(length);
}
計算結果爲6,是錯誤的
正確代碼如下:
public class LengthTest {
public static void main(String[] args) {
String userName = "大中國zxc";
int length = length(userName);
System.out.println(length);
}
public static int length(String value) {
int valueLength = 0;
String chinese = "[\u0391-\uFFE5]";
/* 獲取字段值的長度,如果含中文字符,則每個中文字符長度爲2,否則爲1 */
for (int i = 0; i < value.length(); i++) {
/* 獲取一個字符 */
String temp = value.substring(i, i + 1);
/* 判斷是否爲中文字符 */
if (temp.matches(chinese)) {
/* 中文字符長度爲2 */
valueLength += 2;
} else {
/* 其他字符長度爲1 */
valueLength += 1;
}
}
return valueLength;
}
}
計算結果爲9,上例中代碼可以通用,在開發中如需計算字符串長度,可以參考使用