他实现的方式就是由于String底部是char数组则设定两个采用两个计数器st、len,初始值st=0,len=String.length(),然后从这个char数组两边依次分别拿出每个字符跟' '比较,只要小于或者等于它,就将st加1,len减1,知道不符合条件。说明已经将空格字符去掉完毕。下面是String中trim的源码,
public final class String
implements java.io.Serializable, Comparable<String>, CharSequence
{
private final char value[];
private final int offset;
private final int count;
private int hash; // Default to 0
public String(char value[]) {
int size = value.length;
this.offset = 0;
this.count = size;
this.value = Arrays.copyOf(value, size);
}
public String trim() {
int len = count;
int st = 0;
int off = offset; /* avoid getfield opcode */
char[] val = value; /* avoid getfield opcode */