1. Practical Skills JAVA Implementation in Web (4)
Public static int getbyteslength (string S, string encode ){
If (S = NULL ){
Return 0;
}
Byte [] bytes;
If (encode = NULL ){
Bytes = S. getbytes ();
} Else {
Try {
Bytes = S. getbytes (encode );
} Catch (unsupportedencodingexception e ){
Bytes = S. getbytes ();
}
}
Return bytes. length;
}
Public static string intercept (string S, int length, string encode ){
Stringbuffer sb = new stringbuffer (s );
Int Len = getbyteslength (S, encode );
While (LEN> length ){
SB. deletecharat (sb. tostring (). Length ()-1 );
Len = getbyteslength (sb. tostring (), encode );
}
Return sb. tostring ();
}
L in Java, the string object provides the getbytes () method to convert the string into a byte array. You can obtain the number of bytes through its Length attribute.
L note that the number of bytes of the full-width characters is usually 2; but the number of bytes of some special characters (for example, ①) is 1 or 2, which is determined by getbytes () the specified character encoding is determined by the specific situation. If no character encoding is specified, the system encoding is used.