oud*_*ouz 1 java string whitespace space
问题很清楚.代码应该是Java而不使用正则表达式(如果有人没有注意到,那不是重复,我要求一种方法来做到没有正则表达式).
input: This is a string with more than one space between words.
output: This is a string with more than one space between words.
Run Code Online (Sandbox Code Playgroud)
有没有比这样做更好的方法?
public static String delSpaces(String str){
StringBuilder sb = new StringBuilder(str);
ArrayList<Integer> spaceIndexes = new ArrayList<>();
for ( int i=0; i < sb.length(); i++ ){
if ( sb.charAt(i) == ' ' && sb.charAt(i-1) == ' '){
spaceIndexes.add(i);
}
}
for (int i = 0; i < spaceIndexes.size(); i++){
sb.deleteCharAt(spaceIndexes.get(i)-i);
}
return new String(sb.toString());
}
Run Code Online (Sandbox Code Playgroud)
Rus*_*tam 11
使用 str.replaceAll("\\s+"," ");//使用正则表达式的最简单方法
第二种方式:
public static String delSpaces(String str){ //custom method to remove multiple space
StringBuilder sb=new StringBuilder();
for(String s: str.split(" ")){
if(!s.equals("")) // ignore space
sb.append(s+" "); // add word with 1 space
}
return new String(sb.toString());
}
Run Code Online (Sandbox Code Playgroud)
第三种方式:
public static String delSpaces(String str){
int space=0;
StringBuilder sb=new StringBuilder();
for(int i=0;i<str.length();i++){
if(str.charAt(i)!=' '){
sb.append(str.charAt(i)); // add character
space=0;
}else{
space++;
if(space==1){ // add 1st space
sb.append(" ");
}
}
}
return new String(sb.toString());
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
18017 次 |
| 最近记录: |