adding space in between every word in java

I have a string that could look like this where there could be one or more spaces in between the words and this is just a sample of it

JAVA CODE STYLING AND RESOURCES

How can I insert/append white spaces in between every word using java to achieve this result

JAVA   CODE  STYLING  AND  RESOURCES

from the above u can see that additional white spaces was added because there is a space already after the words except the last.

On my own, I have attempted and all I could arrive is adding spaces after every character instead of words having one or more white spaces

Answer

Strictly speaking, if you really only want to add a space to a space which already exists in between words, you can match on the following regex pattern:

(?<=w)([ ]+)(?=w)

And then replace with the captured spaces along with one additional space. Here is a sample script:

String input = "JAVA CODE STYLING AND RESOURCES";
String output = input.replaceAll("(?<=\w)([ ]+)(?=\w)", "$1 ");
System.out.println(input);  // JAVA CODE STYLING AND RESOURCES
System.out.println(output); // JAVA  CODE  STYLING  AND  RESOURCES

Leave a Reply

Your email address will not be published. Required fields are marked *