获取字符串已utf-8表示的字节数

时间:2022-10-15 16:53:12
 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"),但是效率方面肯定不如上面的代码