String 类有个方法去除字符串首位空格: str.trim();
查看源代码:
public String trim() {
int len = value.length;
int st = ;
char[] val = value; /* avoid getfield opcode */ while ((st < len) && (val[st] <= ' ')) {
st++;
}
while ((st < len) && (val[len - ] <= ' ')) {
len--;
}
return ((st > ) || (len < value.length)) ? substring(st, len) : this;
}
自个编写:
public static String getTrim(String str){ char[] val = str.toCharArray();
int len = val.length, st = ; while( ( st < len ) && (val[st] == ' ') )
st++;
while( ( st < len ) && (val[len-] == ' ') )
len--; return ( ( len < val.length ) && ( st > ) ) ? str.substring(st,len):str; }