在項目開發中經常碰到到輸入字元的校驗,特别是中英文混合在一起的校驗。而為了滿足校驗的需求,有時需要計算出中英文的長度。
本文将通過幾種常用的方法實作長度的計算:
public class StringLengthTest {
private static long startTime;
public static void main(String[] args) {
String validateStr = "中英文校驗abcde接口ii";
for (int i = 0; i < 10; i++) {
validateStr = validateStr + validateStr;
}
int bytesStrLength = getBytesStrLength(validateStr);
int chineseLength = getChineseLength(validateStr);
int regexpLength = getRegExpLength(validateStr);
System.out.println("length:" + validateStr.length());
System.out.println("getBytesLength:" + bytesStrLength
+ ",chineseLength:" + chineseLength + ",regexpLength:"
+ regexpLength);
}
public static int getBytesStrLength(String validateStr) {
startTime = System.currentTimeMillis();
String tempStr = "";
try {
tempStr = new String(validateStr.getBytes("gb2312"), "iso-8859-1");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
System.out.println("getBytesStrLength time:"
+ (System.currentTimeMillis() - startTime));
return tempStr.length();
}
public static int getChineseLength(String validateStr) {
startTime = System.currentTimeMillis();
int valueLength = 0;
String chinese = "[\u0391-\uFFE5]";
for (int i = 0; i < validateStr.length(); i++) {
String temp = validateStr.substring(i, i + 1);
if (temp.matches(chinese)) {
valueLength += 2;
} else {
valueLength += 1;
}
}
System.out.println("getChineseLength time:"
+ (System.currentTimeMillis() - startTime));
return valueLength;
}
public static int getRegExpLength(String validateStr) {
startTime = System.currentTimeMillis();
// String temp = validateStr.replaceAll("[\u4e00-\u9fa5]", "**");
String temp = validateStr.replaceAll("[^\\x00-\\xff]", "**");
System.out.println("getRegExpLength time:"
+ (System.currentTimeMillis() - startTime));
return temp.length();
}
}
結果:
getBytesStrLength time:2
getChineseLength time:30
getRegExpLength time:11
length:14336
getBytesLength:21504,chineseLength:21504,regexpLength:21504
建議:
使用 方式三:利用正規表達式 方式
方式一:根據字元編碼 位元組數生成一個臨時的字元串(需要确定字元編碼,不同編碼結果長度不同)
方式二:擷取字元串的長度,如果有中文,則每個中文字元計為2位(比較耗時)