-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.

0

1 Answer 1

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
Sign up to request clarification or add additional context in comments.

1 Comment

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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.