MohanSingh MohanSingh - 2 years ago 85
Java Question

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

I stuck at solve following code.

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

In string s , the more than one space is not known. But i need to print it as
%temp%Hello I'm a%temp%multi spaced String

How to do this?

Thanks in advance friends.

rD. rD.
Answer Source

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



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


public class HelloWorld
  public static void main(String[] args)
    String s = "    Hello I'm a       multi spaced String";
    s = s.replaceAll("\\s{2,}","%temp%");
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download