几道java面试题讨论
问题2,编写一个字符串截取程序,要求按字节长度截取一个字节数组形势的字符串,字符包含中英文,要求最后截取的是半个中文字符,舍弃它,看大家有没有好的算法。
[解决办法]
String str = "我ABC汉DEF";
int isize = 7;
int endIndex = isize / 2;
String sub = str.substring(0, endIndex);
while (sub.getBytes().length < isize) {
if (isize - sub.getBytes().length >= 2) {
endIndex = endIndex + (isize - sub.getBytes().length) / 2;
} else {
endIndex++;
}
String temp = str.substring(0, endIndex);
if (temp.getBytes().length - 1 == isize) {
break;
} else {
sub = temp;
}
}
System.out.println(sub);
public class a1 {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
String str="中国A我";
byte[] b="s".getBytes();
new a1().A(str,4);
}
public void A(String str,int i) {
byte b[] = new byte[1024];
int num = 0;
b = str.getBytes();
if(b[i-1]>0) {
System.out.println(new String(b,0,i));
}else {
for(int j=0;j<i;j++) {
if(b[j]<0) {
num++;
num = num%2;
}else {
num = 0;
}
}
if(num==0) {
System.out.println(new String(b,0,i));
}else {
System.out.println(new String(b,0,i-1));
}
}
}
}