Title: 10, write a function to intercept the string, enter a string and the number of bytes, the output is a byte-truncated string. But to ensure that Chinese characters are not truncated half, such as "I abc" 4, should be cut to "I ab", input "I ABC Han def", 6, should be output as "I abc" rather than "I abc+ Han half."
First, need analysis
1, input as a string and number of bytes, output is a byte-truncated string--------------"intercept the action string in bytes [byte], first convert string to byte type
.2, Chinese characters can not be cut half---------------------------------------------------------------------------------------------------------- "The ASC Code of the corresponding byte is less than 0 when the kanji is truncated.
Second, technical difficulties
1, know the Chinese characters truncated half of the corresponding byte ASC code is less than 0 value
2, the string operation should have to face a problem, whether the string is valid null, the length of the string 0,1 this boundary processing
Code implementation:
PackageCom.itheima;/*** 10, write a function to intercept the string, input as a string and number of bytes, the output is a byte-truncated string. * But to ensure that the Chinese character is not truncated half, such as "I abc" 4, should be cut to "I ab", input "I ABC Han def", 6, should be output as "I abc" rather than "I abc+ Han half." * * @author[email protected]*/ Public classTest10 { Public Static voidMain (string[] args) {String srcStr1= "I abc"; String SRCSTR2= "I abc Han def"; Splitstring (SRCSTR1,4); Splitstring (SRCSTR2,6); } Public Static voidSplitstring (String src,intLen) { intBytenum = 0; if(NULL==src) {System.out.println ("The source String is null!"); return; } bytenum=src.length (); byteBt[] = Src.getbytes ();//converts a string to a byte byte array if(Len >bytenum) {Len=Bytenum; } //determine if a truncated, half-truncated byte for the ASC code is less than 0 value if(Bt[len] < 0) {String Substrx=NewString (BT, 0,--Len); System.out.println ("substrx==" +Substrx); } Else{String Substrx=NewString (BT, 0, Len); System.out.println ("substrx==" +Substrx); } }}
Original Blog Address http://blog.csdn.net/zhb123168/article/details/8083936
Interview Java write a function that intercepts a string, input as a string and number of bytes, and output as a byte-truncated string. A condition that requires no truncation