例子:String str = " asd asda123 as ";
test(str); // 打印 "asd asda123 as"
public class trimSpace {
/**
* 去掉开头和结尾的空格,合并中间的空格
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
String temp = " asdkjh askja asd ";
System.out.println(test(temp));
}
private static String test(String str){
String result = "";
for(int i=0;i<str.length();i++){
if(str.substring(i, i+1).equals(" ")==true){
if(result.equals("")==true){
}else{
if(result.equals("")!=true && result.substring(result.length()-1).equals(" ")==true){
continue;
}else{
result = result+str.substring(i, i+1).toString();
}
}
}else{
result = result+str.substring(i, i+1).toString();
}
if(i==str.length()-1){
if(result.substring(result.length()-1).equals(" ")==true){
result = result.substring(0, result.length()-1).toString();
}
}
}
return result;
}
}