- Requirement: Intercept a string containing both Chinese and English in the given number of bytes, and the last byte if the intercept is in Chinese, it is not intercepted, it is intercepted in English.
- The implementation code is as follows (exceptions such as empty strings or illegal bytes are not determined)
1 Importjava.util.ArrayList;2 Importjava.util.List;3 ImportJava.util.Scanner;4 5 /**6 * Created by YCL on 2017-8-18 21:01:16.7 */8 Public classTestA {9 Public Static voidMain (string[] args) {TenScanner sc =NewScanner (system.in); OneSystem.out.println ("String:"); AString str =sc.nextline (); -SYSTEM.OUT.PRINTLN ("Input intercept bytes:"); - intCount =sc.nextint (); the getsubstrbybyte (str, count); - - } - + /** - * @paramSTR receives input in Chinese and English strings + * @paramBytelen receive the number of bytes to intercept A */ at Public Static voidGetsubstrbybyte (String str,intBytelen) { - byte[] bytes =str.getbytes (); - intCount = 0;//the number of bytes that have been traversed -String tempstr = "";//Final Output String -list<byte> list =NewArraylist<byte> ();//temporarily store a list of Chinese characters per byte - for(byteb:bytes) { in if(b >= 0) {//greater than or equal to 0 means English -TempStr + =NewString (New byte[]{b}];//append directly to the output string tocount++; +}Else { -List.add (b);//less than 0 for Chinese and add bytes to the temp list the if(list.size () = = 3) {//when the list length is 3 o'clock, it is converted to a character array, then to a character and appended to the output string * byte[] temp =New byte[3]; $ inti = 0;Panax Notoginseng for(Byte l:list) { -Temp[i] = (byte) L; thei++; + } ATempStr + =NewString (temp); theCount + = 2;//a Chinese byte number plus 2 +List.clear ();//Empty the Temp list - } $ } $ if(count = = Bytelen) {//outputs when the number of bytes traversed equals the number of bytes to be intercepted, and jumps out of the loop - System.out.println (TEMPSTR); - Break; the } - //when the number of bytes traversed = the number of bytes to intercept = 1 o'clock then the last character is Chinese, output and loop outWuyi Else if((Count-bytelen = = 1)) { theSystem.out.println (tempstr.substring (0, Tempstr.length ()-1)); - Break; Wu } - } About } $}
Java intercepts strings containing Chinese and English in the given number of bytes