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
How Will Java Lambda Functions Be Compiled
Calling a Subclass Method from Superclass
Java and Gui - Where Do Actionlisteners Belong According to MVC Pattern
Java Comparison with == of Two Strings Is False
Replace Implicit Wait with Explicit Wait (Selenium Webdriver & Java)
Should I Initialize Variable Within Constructor or Outside Constructor
Hibernate Annotations - Which Is Better, Field or Property Access
Java Code to Convert Byte to Hexadecimal
How to Connect to Oracle Using Service Name Instead of Sid
How to Resolve the "Java.Net.Bindexception: Address Already in Use: Jvm_Bind" Error
Find a Line in a File and Remove It
Using Graphics2D to Overlay Text on a Bufferedimage and Return a Bufferedimage
Resource Leak: 'In' Is Never Closed
How to Iterate Through the Files in a Directory and It's Sub-Directories in Java