-1

A String can contain multiple spaces in a row - I need to replace multiple subsequent spaces by one single space char. The "problem" is that i cant know how many spaces there may encounter. The function I look for shall not only replace the first occurance of a found match, but all multiple equal characters in a String.

I searched a lot on the internet and tried the regex "X*? (X, zero or more times)" which I found unter "Reluctant quantifiers" on https://docs.oracle.com/javase/7/docs/api/java/util/regex/Pattern.html#sum

That didnt work: s1 = s1.replaceAll(" *?", " "); Where s1 = "Hello World"; should be converted to s1 = "Hello World";

I'd be thankful for any help.

Wasi Ahmad
  • 31,685
  • 30
  • 101
  • 155
Severin Klug
  • 703
  • 3
  • 9

1 Answers1

3

You can use replaceAll() that replaces whitespaces with just a single space.

String st = "helllo   world"
System.out.println(st.replaceAll("\\s+"," "))

Output : helllo world
FallAndLearn
  • 3,855
  • 1
  • 15
  • 24
  • The regexp matcher for whitespace is `\\s+` as this answer correctly pointed out. Keep in mind though that `s1.replaceAll("\\s+", " ")` produces a new String as a result. So s1 will remain unchanged and you'll need to assign the result of replaceAll to a new variable in order to make use of the regexp replacement. – Thanos Dec 22 '16 at 09:47