private static int utf8Length(String string) { /** Returns the number of bytes required to write this. */
int stringLength = string.length();
int utf8Length = 0;
for (int i = 0; i < stringLength; i++) {
int c = string.charAt(i);
if (c <= 0x007F) {
utf8Length++;
} else if (c > 0x07FF) {
utf8Length += 3;
} else {
utf8Length += 2;
}
}
return utf8Length;
}
当然我们是可以直接使用String.getBytes("utf-8"),但是效率方面肯定不如上面的代码