In the "
intercepts string length from back to front
," describes how to intercept the string, statistical article describes how the byte length of the string.
Import org.slf4j.Logger; Import org.slf4j.LoggerFactory; Import java.io.UnsupportedEncodingException; public class a GetLength { Private static Final Logger Logger = LoggerFactory.getLogger (a GetLength. class ); // encoding Private static Final String = ENCODE_UTF "UTF-. 8" ; / ** byte length <br/> * calculation English string * a Chinese 3 bytes * * @param STR * @return int byte length of the string * / public static intgetLength (String STR) { IF (STR == null || str.length () == 0 ) { return 0 ; } the try { return str.getBytes (ENCODE_UTF) .length; } the catch (UnsupportedEncodingException E) { logger.error ( "byte string length calculated failure in English," , E); } return 0 ; } / ** * calculation English string length in bytes * * @param STR * @return int * / public static int getStrLength (String STR) { IF (STR == null || str.length () == 0 ) { return 0 ; } int len = 0 ; for ( int I = 0, J = str.length (); I <J; I ++ ) { // UTF encoding format. 8-Chinese accounted three bytes, GBK Chinese encoding format is two bytes; len + = (str.charAt (I)> 255. 3:?. 1 ); } return len; } public static void main (String [] args) { String STR = "Agricultural Bank 3Wiener, pay dense" ; System.out.println(getLength(str)); System.out.println(getStrLength(str)); } }