今天去了一家面试遇到一个问题,不知道该怎么样解决!请高手指点一下!谢谢
已知:一个字符串和要截的位数,然后字符串返回!但要达到这样的效果!
比如:字符串:“我ABC”      要截取4位  效果:“我AB”
      字符串:“我ABC你”    要截取6位  效果:“我ABC”
不能将一个中文的汉字截取成一般  比如“我ABC”+“你”的一半!要保留整个汉字!请兄弟们指教一下!谢谢!

解决方案 »

  1.   

    这个试试public static void getChar(String str, int count) {
            byte[] byteArray = new byte[count];
            byte[] temp = str.getBytes();
            int ii = 0;
            for (int i = 0; i < count; i++) {
                byteArray[i] = temp[i];
                if (temp[i] < 0) {
                    ii++;
                }
            }
            if (ii % 2 == 1) {
                byteArray[count - 1] = ' ';
            }
            System.out.println(new String(byteArray).trim());    }
      

  2.   

    楼上的方法肯定是OK的
    LZ放心使用吧:)
      

  3.   

    可以试试用split("")将字符串分割成数据,然后取数组的length-2个元素重新生成字符串
      

  4.   

    public static String getString(String args,int length){
         if(length>args.length())
         length=args.length();
         String output="";
         byte[] b=args.getBytes();
         if(length/2!=0){
         if(b[length]<0)
         length=length-1;
         }
         output=new String(b,0,length);
         return output;
        }  
      

  5.   

    public class Cut {
        public String cut(String s, int n) {
            String c="";
            String d = "";
            String[] b = s.split("");
            for (int i = 0; i < b.length; i++) {
                c = c + b[i];
                if((c.getBytes().length)==n){
                    d = d + b[i];
                    break;
                }else if((c.getBytes().length)>n){
                    break;
                }
                d = d + b[i];
            }
            return d;
        }    public static void main(String[] args) {
            Cut cu = new Cut();
            String a = cu.cut("a接口cd喊f", 4);
            System.out.println(a);
        }
    }