如何用java写trim函数的方法

解决方案 »

  1.   

    jdk有现成的trim()可用://这是jdk里面的实现
    public String trim() {
    int len = count;
    int st = 0;
    int off = offset;      /* avoid getfield opcode */
    char[] val = value;    /* avoid getfield opcode */ while ((st < len) && (val[off + st] <= ' ')) {
        st++;
    }
    while ((st < len) && (val[off + len - 1] <= ' ')) {
        len--;
    }
    return ((st > 0) || (len < count)) ? substring(st, len) : this;
        }
      

  2.   


    //把jdk里面的实现稍加改造:
    public static String trim(String src) {
            if(src == null){
                return null;
            }
            int count = src.length();
            int len = count;
            int st = 0;
            char[] val = src.toCharArray();         while ((st < len) && (val[st] <= ' ')) {
                st++;
            }
            while ((st < len) && (val[len - 1] <= ' ')) {
                len--;
            }
            return ((st > 0) || (len < count)) ? src.substring(st, len) : src;
        }
      

  3.   

    JDK中有src压缩文件的,自己看源代码
      

  4.   


    //闲的蛋疼,重构一下
    public static String trim(String src) {
            if(src == null){
                return null;
            }
            int start = 0;
            int end = src.length();
            while ((start < end) && (src.charAt(start)<= ' ')) {
                start++;
            }
            while ((start < end) && (src.charAt(end -1)<= ' ')) {
                end--;
            }
            return ((start > 0) || (end < src.length())) ? src.substring(start, end) : src;
        }