分割字符串
需求:编写一个截取字符串的函数,输入一个字符串和字节数,输出为按字节数截取的字符串,但是要保证汉字不能截半个,如“我ABC” 4,应该截为"我AB",输入"我ABC汉DEF" 6,应该输出为"我ABC",而不是"我ABC+汉的半个"。
?
public static void split(String str,int split){System.out.println(str.getBytes().length); if(str.getBytes().length > split){ byte b[] = str.getBytes(); int count = 0; int max = 0; int to = 0; for(int i=0;i<(split);i++){ if(b[i]<0){ count++; //一个汉字是能被2整除的,to是几就表明有几个汉字,to是基数时就 if(count%2 == 0){ //是多了半个汉字。 to = count/2; //2 //str.substring(0,count+max); } }else{ max++;//2 max是英文,有几个英文字母就有几个max; } } System.out.print(str.substring(0,to+max));//然后在截取string字符,从0截的to+max就是要的字符了。 }else{ System.out.println("截取数为太大,请写小点!"); }} public static void main(String args[]){ split("A行王C汉王科技",4); }