Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove spaces in between the String

Tags:

java

string

regex

I have below String

  string = "Book Your Domain And Get\n \n\n \n \n \n Online Today."
  string = str.replace("\\s","").trim();

which returning

  str = "Book Your Domain And Get     Online Today."

But what is want is

  str = "Book Your Domain And Get Online Today."

I have tried Many Regular Expression and also googled but got no luck. and did't find related question, Please Help, Many Thanks in Advance

like image 260
Lav patel Avatar asked Sep 18 '13 10:09

Lav patel


People also ask

How do I remove spaces between strings in Java?

Java has inbuilt methods to remove the whitespaces from the string, whether leading, trailing, both, or all. trim() method removes the leading and trailing spaces present in the string. strip() method removes the leading and trailing spaces present in the string.

How do I remove spaces from Excel strings?

You can also remove spaces using the Find/Replace feature in Excel. Click CTRL+F to open the Find dialog box, then click the Replace tab. Enter one space ” ” in the Find what: field and leave the Replace with: field empty to remove all spaces.


1 Answers

Use \\s+ instead of \\s as there are two or more consecutive whitespaces in your input.

string = str.replaceAll("\\s+"," ")
like image 156
Rafi Kamal Avatar answered Oct 20 '22 20:10

Rafi Kamal