MohanSingh MohanSingh - 3 months ago 11
Java Question

How do I insert a word if the string has more than one space in Java?

I have the following code,

String s = " Hello I'm a multi spaced String"


In string s, there are multiple (indeterminate) spaces; but, I need to print it as
%temp%Hello I'm a%temp%multi spaced String


How can I do this?

rD. rD.
Answer

Use regex \s{2,} and replaceAll() method like this:

s.replaceAll("\\s{2,}","%temp%");

Output

%temp%Hello I'm a%temp%multi spaced String

Code

public class HelloWorld
{
  public static void main(String[] args)
  {
    String s = "    Hello I'm a       multi spaced String";
    s = s.replaceAll("\\s{2,}","%temp%");
    System.out.println(s);
  }
}