日期:2014-05-20  浏览次数:20649 次

几道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));
}
}



}
}

------解决方案--------------------

public static String myCuter(String input,int length){
int inputStrLength=input.length();
byte [] bs=input.getBytes();
int byteLen=bs.length;

if(byteLen<length){
System.out.println("out of range!");
return null;
}

int strOffset=0;
int byteOffset=0;
StringBuffer sb=new StringBuffer();
while(strOffset<inputStrLength){
String temp=input.substring(strOffset,strOffset+1);
byteOffset+=temp.getBytes().length;

if(byteOffset>length)
break;
else{
sb.append(temp);
strOffset++;
}
}
return sb.toString();
}