Lotun Kanji
Lotun Kanji

Reputation: 73

How to get rid of multiple spaces in a string and leave one

I am trying to make a method where it "fixes" sentences. So, for example, if the sentence is " the Cookie is BROwN" it will return "The cookie is brown.". Right now I am trying to work on the "space fixer" part, where multiple spaces will be analyzed and turn into a single space. This is the code I have so far. Could someone tell me how I can go about fixing the spaces and getting rid of unecessary spaces? I know it is not complete yet. I am currently just trying to fix the spaces. Here is my code below.

    public static String sentenceRepair(String sentence){
    String finale="";
    for (int x=0;x<sentence.length();x++){
        char a= sentence.charAt(x);
        if (sentence.charAt(x)==' '){       //SPACE CHECKER!!
            if((x!=0&&x!=sentence.length())&&(sentence.charAt(x-1)==' '||sentence.charAt(x+1)==' ')){
                sentence.charAt(x)="";
            }
        }
    }
    return finale;
}

Upvotes: 0

Views: 78

Answers (2)

Scorix
Scorix

Reputation: 609

your version is much more complicated than it needs to be

String str = " hello     there   ";
str = str.replaceAll("( +)"," ").trim());

This code replaces all multiple spaces with one space and deletes every spaces in front of and at the end of the String using a regex "code"

Upvotes: 0

gawi
gawi

Reputation: 2952

I would use regex:

public static String sentenceRepair(String sentence){
  return sentence.replaceAll(" +", " ");
}

Upvotes: 1

Related Questions