public class TestSubString { public static void main(String[] args) { String a = "abc hello 123"; a = subStr(a,6); System.out.println(a); } public static String subStr(String str ,int end){ int length=0; char[] ch = str.toCharArray(); String str2 = ""; for(int i =0;i<str.length();i++){ // int num = Character.codePointAt( ch,i); // int num = Character.codePointAt( str,i); int num = str.codePointAt(i); //The effect of changing the line of code is the same as that of the previous two lines of code, get the current Iterate over the values of the elements. Less than or equal to 255 is one byte, and more than 255 is two bytes if(num>=0&&num<=255){ length++;//The number of bytes plus 1
}else{ length+=2;//Add 2 to the number of bytes } if(length<end){ //Continue to loop if the intercepted byte length is not reached, and connect the traversed elements with the str string str2+=ch[i]; }else if(length==end){ //just reach the intercepted byte length, exit the loop, and connect the traversed elements with the str string str2+=ch[i]; break; }else{ //Exceed the length, It is because the current traversal is a Chinese character element, and half of the Chinese character is not intercepted, so it exits the loop directly. break; } } return str2; return the new spliced string } }
The string is intercepted by bytes
Guess you like
Origin blog.csdn.net/Angle_Byron/article/details/130971232
Recommended
Ranking