Given a string of characters. Groups of characters in it are separated by spaces. Remove extra spaces between words, leaving only one. (java) (NetBeans)

  • @ Алексей1526 A 1526 is the year of birth? Will beat your question. Does not comply with the rules - alexlz
  • such things are done by the state machine. In this case, the machine has 2 states (was the previous character a space). - rfq

4 answers 4

Why complicate things?

System.out.println("Твой текст тут".replaceAll("[\\s]{2,}", " ")); 
  • And square brackets seem to be superfluous? - Qwertiy
  • one
    Instead of "[\\s]{2,}" you can use "\\s+" . - ForNeVeR

It can be a regular expression, for example

 private static final Pattern CLEAR_PATTERN = Pattern.compile("[\\s]+"); ... CLEAR_PATTERN .matcher(result).replaceAll(" ").trim(); 

    Without regular expressions would be like this:

     final String twoSpaces=" "; final String oneSpace=" "; String myText; //наша строка while(myText.indexOf(twoSpaces) >= 0) { myText.replace(twoSpaces, oneSpace); } 

    With regexp'ami which I personally do not like - the people will add.

    PS I'm good today.

       String x = "парам пам пам пам пам"; while(x.contains(" ")) { String replace = x.replace(" ", " "); x=replace; } System.out.println(x); 
      • Try to write more detailed answers. Explain what is the basis of your statement? - Nicolas Chabanovsky