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

今天下午南通 江苏中威 的机试题(CoreJava)
1 编写一个截取字符串的函数,输入为一个字符串的字节数,输出为按字节截取的字符串。

  但是要保证汉字不被截半个,如“我ABC” 4 , 应该截为“我AB”,

  输入“我ABC汉DEF”6 ,应该输出为“我ABC”,而不是“我ABC+汉的半个”。

------解决方案--------------------
上面那些没有优化,n就是 要截取的长度..

str就是原始的, 最后输出的 就是 结果了.
------解决方案--------------------
首先要了解中文字符有多种编码及各种编码的特征。
假设n为要截取的字节数。
public static void main(String[] args) throws Exception{
String str = "我a爱中华abc我爱传智def';
String str = "我ABC汉";
int num = trimGBK(str.getBytes("GBK"),5);
System.out.println(str.substring(0,num) );
}

public static int trimGBK(byte[] buf,int n){
int num = 0;
boolean bChineseFirstHalf = false;
for(int i=0;i<n;i++)
{
if(buf[i]<0 && !bChineseFirstHalf){
bChineseFirstHalf = true;
}else{
num++;
bChineseFirstHalf = false;
}
}
return num;
}

------解决方案--------------------
Java code

  public static void split(String source,int num) throws Exception
  {
    int k=0;
    String temp="";
    for (int i = 0; i <source.length(); i++)
    {
      byte[] b=(source.charAt(i)+"").getBytes();
      k=k+b.length;
      if(k>num)
      {
        break;
      }
      temp=temp+source.charAt(i);
    }
    System.out.println(temp);
  }

------解决方案--------------------
Java code

    public static void main(String[] args) {
        String str = "我ABC汉DEF";
        System.out.println(subString(str, 6));
    }

    public static String subString(String str, int length){
        char[] chars = str.toCharArray();
        int temp = 0;
        int index = 0;
        while(temp <= length){
            if(index >= chars.length)
                return str;
            if(chars[index++] > 255)
                temp += 2;
            else
                temp += 1;
        }
        return str.substring(0, index - 1);
    }