Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

string

regex

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?

like image 923
Rajamohan S Avatar asked Aug 21 '16 04:08

Rajamohan S


People also ask

How do I add multiple spaces to a string in Java?

One way to do this is with string format codes. For example, if you want to pad a string to a certain length with spaces, use something like this: String padded = String. format("%-20s", str);

How do you replace multiple spaces with one space in a string Java?

The metacharacter “\s” matches spaces and + indicates the occurrence of the spaces one or more times, therefore, the regular expression \S+ matches all the space characters (single or multiple). Therefore, to replace multiple spaces with a single space.

How do you replace extra spaces in Java?

To remove leading and trailing spaces in Java, use the trim() method. This method returns a copy of this string with leading and trailing white space removed, or this string if it has no leading or trailing white space.

How do I split a string with one or more spaces?

To split a string by multiple spaces, call the split() method, passing it a regular expression, e.g. str. trim(). split(/\s+/) . The regular expression will split the string on one or more spaces and return an array containing the substrings.


2 Answers

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);
  }
}
like image 88
Raman Sahasi Avatar answered Sep 20 '22 23:09

Raman Sahasi


You can use a regular expression like \s\s+ which matches a white space followed by one or more additional whitespaces. Something like,

String s = "    Hello I'm a       multi spaced String";
s = s.replaceAll("\\s\\s+", "%temp%");
System.out.println(s);

Outputs (as requested)

%temp%Hello I'm a%temp%multi spaced String
like image 40
Elliott Frisch Avatar answered Sep 17 '22 23:09

Elliott Frisch