一道面试题 的正解 保证汉字不被截半个

来源:互联网 发布:json好处 编辑:程序博客网 时间:2024/06/04 19:53
  1. public class Test  
  2.     public static void main(String[] args){  
  3.             
  4.         String s = "我ABC汉DEF";  
  5.   
  6.         int length=6;  
  7.         String s2 = subString(s, length);  
  8.         if(s.indexOf(s2)==-1){  
  9.             s2 = subString(s, length-1);  
  10.         };  
  11.         System.out.println("正确答案:"+s2.trim());  
  12.     }  
  13.   
  14.     private static String subString(String s, int bl) {  
  15.         byte[] bytes = s.getBytes();  
  16.         byte[] newbytes = new byte[128];                      
  17.         for ( int i =0; i<bl;i++) {  
  18.             byte b =bytes[i];  
  19.             newbytes[i]=b;  
  20.               
  21.         }  
  22.         return  new String(newbytes);             
  23.     }  
  24. }