获取字符串已utf-8表示的字节数
1 private static int utf8Length(String string) { /** Returns the number of bytes required to write this. */ 2 int stringLength = string.length(); 3 int utf8Length = 0; 4 for (int i = 0; i < stringLength; i++) { 5 int c = string.charAt(i); 6 if (c <= 0x007F) { 7 utf8Length++; 8 } else if (c > 0x07FF) { 9 utf8Length += 3; 10 } else { 11 utf8Length += 2; 12 } 13 } 14 return utf8Length; 15 }
当然我们是可以直接使用String.getBytes("utf-8"),但是效率方面肯定不如上面的代码