Java How to Replace 2 or More Spaces with Single Space in String and Delete Leading and Trailing Spaces

Java string method that replaces all sequences of 2 or more spaces with a single space

You don't really need the booleans. Just keep track of the indices. Keep in mind that removing characters one at a time is expensive because there is quite a bit of array copying under the hood with these StringBuilder methods.

One more subtlety. When you iterate from the beginning and delete characters, all characters move to the left one spot. This can require additional bookkeeping. To solve this you iterate from the right. Then when you delete a character, it doesn't affect the relative positions of the characters further to the left.

      String sampleText = "This    is    a  test of    removing extra spaces";
StringBuilder sampleTextBuilder = new StringBuilder(sampleText);
for (int i = sampleTextBuilder.length() - 1; i >= 0; i--) {
if (sampleTextBuilder.charAt(i) == ' ') {
// found a space, check front and back of string.
if (i == sampleTextBuilder.length() - 1 || i == 0) {
sampleTextBuilder.deleteCharAt(i);
}
// otherwise, delete one of them if two are present.
else if (sampleTextBuilder.charAt(i - 1) == ' ') {
sampleTextBuilder.deleteCharAt(i - 1);
}
}
}
sampleText = sampleTextBuilder.toString();
System.out.println("\"" + sampleText + "\"");

Given a sentence with multiple spaces between words. Remove the extra spaces so that the sentence will have exactly one space between words

use str.replaceAll("\\s+"," "); // simplest way using regular expression

2nd way :

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());
}

3rd way :

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());
}


Related Topics



Leave a reply



Submit