java-给定字符串,删除开始和结尾处的空格,并将中间的多个连续的空格合并成一个。...



public class DeleteExtraSpace {

/**
* 题目:给定字符串,删除开始和结尾处的空格,并将中间的多个连续的空格合并成一个。
* 方法1.用已有的String类的trim和replaceAll方法
* 方法2.全部用正则表达式,这个我不熟
* 方法3.“重新发明轮子”,从头遍历一次
*/
public static void main(String[] args) {

String[] strs={
"",
" ",
"a",
" hello world ",
};
for(String str:strs){
String str2=str.trim().replaceAll(" +", " ");
System.out.println(str2+",length2="+str2.length());

String str3=deleteExtraSpace(str);
System.out.println(str3+",length3="+str3.length());

System.out.println(str2.equals(str3));
System.out.println("=========================");
}

}

public static String deleteExtraSpace(String str){
if(str==null){
return null;
}
if(str.length()==0 || str.equals(" ")){
return new String();
}
char[] oldStr=str.toCharArray();
int len=str.length();
char[] tmpStr=new char[len];
boolean keepSpace=false;
int j=0;//the index of new string
for(int i=0;i char tmpChar=oldStr[i];
if(oldStr[i]!=' '){
tmpStr[j++]=tmpChar;
keepSpace=true;
}else if(keepSpace){
tmpStr[j++]=tmpChar;
keepSpace=false;
}
}

//unlike c/c++,no "\0" at the end of a string. So,do the copy again...
int newLen=j;
if(tmpStr[j-1]==' '){
newLen--;
}
char[] newStr=new char[newLen];
for(int i=0;i newStr[i]=tmpStr[i];
}
return new String(newStr);
}
}

你可能感兴趣的:(面试题)