0

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;
}
  • 1
    I think this is **duplication** of this one: https://stackoverflow.com/questions/3958955/how-to-remove-duplicate-white-spaces-in-string-using-java/41291983#41291983 – Oleg Cherednik May 06 '18 at 21:16

2 Answers2

1

I would use regex:

public static String sentenceRepair(String sentence){
  return sentence.replaceAll(" +", " ");
}
gawi
  • 2,843
  • 4
  • 29
  • 44
0

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"

Scorix
  • 487
  • 6
  • 20