package test; /** * 编程:编写一个截取字符串的函数,输入为一个字符串和字节数, * 输出为按字节截取的字符串。 * 但是要保证汉字不被截半个,如"我ABC"4,应该截为"我AB", * 输入"我ABC汉DEF",6,应该输出为"我ABC"而不是"我ABC+汉的半个"。 * * @author HF * */ class SplitString { public String mySplit(String splitStr, int length){ byte[] bytes = splitStr.getBytes(); if(length<=0&&length>bytes.length){ return ""; } int[] type = new int[bytes.length]; System.out.println("String byte Array lenth :" + bytes.length); for(int i =0;i<bytes.length;){ if(bytes[i]<0){ //汉字 type[i++] = 1; //汉高 type[i++] = 2; //汉低 }else{//英文 i++; type[i-1] = 0;//英 } } int realLen =0; if(type[length-1]==1){ //汉高 realLen = length -1; }else{ //汉低or英 字节 realLen = length; } return new String(bytes,0,realLen); } public static void main(String args[]) { String str = "a我ads汉DEFe呀fgsdfg大撒旦"; int num = 8; SplitString sptstr = new SplitString(); System.out.println(sptstr.mySplit(str, num)); } }