Source code:
Public class demo {public static void main (string [] ARGs) {string src = "difficult Java, programmer. "; // String Length: system. out. println ("src length:" + SRC. length (); // The number of characters contained in the string: system. out. println ("src length constains CHAR:" + fetchcharnumber (SRC); // number of bytes contained in the string system. out. println ("src constains byte:" + SRC. getbytes (). length);}/*** calculates the length of the string. ** @ Param SRC the string to be calculated * @ return-1 indicates that the input SRC is a null value */public static int fetchcharnumber (string SRC) {int counter =-1; if (SRC! = NULL) {counter = 0; Final int Len = SRC. length (); For (INT I = 0; I <Len; I ++) {char sigleitem = SRC. charat (I); If (isalphanumeric (sigleitem) {counter ++;} else if (character. isletter (sigleitem) {counter = counter + 2;} else {counter ++ ;}}} else {counter =-1 ;}return counter ;} /*** determines whether the character is an English letter or an Arabic number. ** @ Param ch char character * @ return true or false */public static Boolean isalphanumeric (char ch) {// constant defines final int digital_zero = 0; Final int digital_nine = 9; final char min_lowercase = 'a'; Final char max_lowercase = 'Z'; Final char min_uppercase = 'a'; Final char max_uppercase = 'Z '; if (CH> = digital_zero & Ch <= digital_nine) | (CH> = min_lowercase & Ch <= max_lowercase) | (CH >= min_uppercase & Ch <= max_uppercase) {return true ;}else {return false ;}}}
Java is hard-pressed, program ape.
Including: 4 letters (Java) + 1 space + 3 Chinese characters + 1 English comma + 2 Chinese characters + 1 space + 1 Chinese Character + 1 Chinese Character full stop
The Length attribute of string treats Chinese characters and English characters, numbers, punctuation marks, and spaces as one.
So, length = 14
In Java, Chinese characters account for 2 char characters, and all punctuation marks, letters, numbers, and spaces account for 1 char.
So, char = 20
By default, Chinese or Chinese Punctuation Marks are encoded in Java, and English letters or punctuation marks are encoded in 1 byte.
Then, byte = 4x1 + 1x1 + 3x3 + 1x1 + 2x3 + 1x1 + 1x3 + 1x3 = 28
Print result:
Note:
// False system. out. println (character. isletter (''); // true system. out. println (character. isletter ('A'); // true system. out. println (character. isletter ('A'); // false system. out. println (character. isletter ('. '); // True system. out. println (character. isletter ('my'); // false system. out. println (character. isletter (','));
Character. isletter method. True is returned only when it is a Chinese character or a letter.