Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delete certain blanks

Tags:

java

string

How to change the textstring

New York, Apple Tree, Banana , Marc Polo

to

New York,Apple Tree,Banana,Marc Polo

I have no idea about how to delete certain blanks which is not between two words.

Any help?

like image 596
Ferry Avatar asked Aug 10 '26 14:08

Ferry


2 Answers

Try replaceAll with a regular expression that matches a comma and the surrounding whitespaces and replaces it with just the comma:

s = s.replaceAll("\\s*,\\s*", ","); 

See it working online: ideone

Note: This won't remove spaces at the beginning or end of the line. To remove those too you could modify the regular expression, but simpler is to just call String.Trim afterwards.

like image 167
Mark Byers Avatar answered Aug 13 '26 04:08

Mark Byers


You can either replace (commas surrounded by whitespace) with just commas, or Split on commas, then join the trimmed results.

like image 45
Dave Newton Avatar answered Aug 13 '26 05:08

Dave Newton