直接上代码了
/** ======================================
* Copyright (c) 2015, NSNG All Rights Reserved.
* Date:2015年3月13日 下午1:56:22
*/
package test;
public class TestLen {
public static void main(String[] args) {
System.out.println(TestLen.getWordCount("a"));
System.out.println(TestLen.getWordCount("啊"));
System.out.println(TestLen.getWordCount("a啊"));
}
/**
* 获取字符串字节数
*/
public static int getWordCount(String s) {
int length = 0;
for (int i = 0; i < s.length(); i++) {
int ascii = Character.codePointAt(s, i);
if (ascii >= 0 && ascii <= 255)
length++;
else
length += 2;
}
return length;
}
/**
* [正则表达式]获取字符字节数
*/
public static int getWordCountByReg(String s) {
s = s.replaceAll("[^\\x00-\\xff]", "**");
int length = s.length();
return length;
}
}