package programming;
public class Main9 {
public static void main(String[] args) {
String str="我ABC汉DEF";
str=cutString(str,6);
System.out.println("截取的字符串:"+str);
}
//通过字节数截取字符串
private static String cutString(String str, int i) {
String tempStr=null;
StringBuilder resultStr=new StringBuilder();
int len=0;
int sum=0;
for(int j=0;j<str.length();j++){
tempStr=String.valueOf(str.charAt(j));
len=tempStr.getBytes().length;
//判断是否是汉字
if(len>1){
sum=sum+len;
//判断字节数是否已越界
if(sum<=i){
resultStr.append(tempStr);
}else{
break;
}
}else{
sum=sum+1;
if(sum<=i){
resultStr.append(tempStr);
}else{
break;
}
}
}
return resultStr.toString();
}
}