Ferry
Ferry

Reputation: 583

Delete certain blanks

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?

Upvotes: 2

Views: 92

Answers (2)

Mark Byers
Mark Byers

Reputation: 837926

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.

Upvotes: 8

Dave Newton
Dave Newton

Reputation: 160170

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

Upvotes: 4

Related Questions