package myTest.string;//去掉字符串两端的空格;
public class test1_subString { public static void main(String[] args) {
// TODO Auto-generated method stub
String str=" abcdefj ";
trim(str);
}
public static void trim(String str){t
int startIndex=0;
int endIndex=str.length()-1;
while(startIndex<endIndex && str.charAt(startIndex)==' '){startIndex++;}//当从0界标起截取字符串的字符为空,则界标加一;直到截取的字符不为空循环就停止;
while(startIndex<endIndex &&str.charAt(endIndex)==' '){endIndex--;}//当从最后一个字符的index界标起截取字符串的字符为空,则界标减一;直到截取的字符不为空循环就停止;
String s=str.substring(startIndex, endIndex);
System.out.println(s);
}
}
public class test1_subString { public static void main(String[] args) {
// TODO Auto-generated method stub
String str=" abcdefj ";
trim(str);
}
public static void trim(String str){t
int startIndex=0;
int endIndex=str.length()-1;
while(startIndex<endIndex && str.charAt(startIndex)==' '){startIndex++;}//当从0界标起截取字符串的字符为空,则界标加一;直到截取的字符不为空循环就停止;
while(startIndex<endIndex &&str.charAt(endIndex)==' '){endIndex--;}//当从最后一个字符的index界标起截取字符串的字符为空,则界标减一;直到截取的字符不为空循环就停止;
String s=str.substring(startIndex, endIndex);
System.out.println(s);
}
}
String 类的 trim 实现的就已经很好了 public String trim() {
int len = value.length;
int st = 0;
char[] val = value; /* avoid getfield opcode */ while ((st < len) && (val[st] <= ' ')) {
st++;
}
while ((st < len) && (val[len - 1] <= ' ')) {
len--;
}
return ((st > 0) || (len < value.length)) ? substring(st, len) : this;
}
String str=str.replaceAll(" +(\\w+) +","$1");
System.out.print(str.replace(" ", ""));
结果:神马