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

java 字符串为题 一个面试题
编程:编写一个截取字符串的函数,输入为一个字符串和字节数,输出为按字节截取的字符串。 但是要保证汉字不被截半个,如“我ABC”4,应该截为“我AB”,输入“我ABC汉DEF”,6,应该输出为“我ABC”而不是“我ABC+汉的半个”。

------解决方案--------------------
论坛 以前有一模一样的题
------解决方案--------------------
Java code
public class test{   
  public void splitIt(String splitStr, int bytes) { 
  int cutLength = 0; 
  int byteNum = bytes; 
  byte bt[] = splitStr.getBytes(); 
  System.out.println("Length of this String ===>" + bt.length); 
  if (bytes > 1) { 
  for (int i = 0; i < byteNum; i++) { 
  if (bt[i] < 0) { 
  cutLength++; 

  } 
  } 

  if (cutLength % 2 == 0) { 
  cutLength /= 2; 
  }else 
  { 
  cutLength=0; 
  } 
  } 
  int result=cutLength+--byteNum; 
  if(result>bytes) 
  { 
  result=bytes; 
  } 
  if (bytes == 1) { 
  if (bt[0] < 0) { 
  result+=2; 

  }else 
  { 
  result+=1; 
  } 
  } 
  String substrx = new String(bt, 0, result); 
  System.out.println(substrx); 

  } 

  public static void main(String args[]) { 
  String str = "我abc的DEFe呀fgsdfg大撒旦"; 
  int num =3; 
  System.out.println("num:" + num); 
  test sptstr = new test(); 
  sptstr.splitIt(str, num); 
  } 

  }

运行情况:
num:3 
Length of this String ===>25 
我a 

num:2 
Length of this String ===>25 
我 

num:1 
Length of this String ===>25 
我 

num:4 
Length of this String ===>25 
我ab

------解决方案--------------------
混个分~时刻警醒不能眼高手低~~
Java code

    public static void main(String[] args) throws IOException {
        int cnt = 7;
        BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in));
        char[] c = stdIn.readLine().toCharArray();
        int already = 0;//计数器.汉字+2其它+1
        for (int i = 0; i < cnt; i++) {
            if (i >= c.length || already > cnt)
                break;
            char cc = c[i];
            if ((cc >>= 8) == 0)
                already += 2;
            else
                already += 1;
            System.out.print(c[i]);
        }
    }