public static int utf8Length ( String string ) { CharacterIterator iter = new StringCharacterIterator ( string ) ; char ch = iter . first ( ) ; int size = 0 ; while ( ch != CharacterIterator . DONE ) { if ( ( ch >= 0xD800 ) && ( ch < 0xDC00 ) ) { // surrogate pair? char trail = iter . next ( ) ; if ( ( trail > 0xDBFF ) && ( trail < 0xE000 ) ) { // valid pair size += 4 ; } else { // invalid pair size += 3 ; iter . previous ( ) ; // rewind one } } else if ( ch < 0x80 ) { size ++ ; } else if ( ch < 0x800 ) { size += 2 ; } else { // ch < 0x10000, that is, the largest char value size += 3 ; } ch = iter . next ( ) ; } return size ; }
For the given string returns the number of UTF - 8 bytes required to encode the string .