Reputation: 233
Say, I have a string like the first line and I need to convert it to the second line.
"English ,Spanish ,Eastern Japanese "
"English,Spanish,Eastern Japanese"
As you see, there are several whitespaces before commas, but each element may have spaces between its variables, too (like "Eastern Japanese"). So, all I need is to delete multiple whitespaces coming before commas. I can trim the last occuring whitespaces before using replaceAll()
method, that is no problem.
Upvotes: 0
Views: 70
Reputation: 626845
You can remove excessive spaces with replaceAll
:
String s = "English ,Spanish".replaceAll("\\s+,",",");
See IDEONE demo
Or with trim()
:
System.out.println("English ,Spanish ".replaceAll("\\s+,",",").trim());
Another demo
And another hint: if there are spaces to trim after ,
, add \\s*
after ,
in the pattern:
.replaceAll("\\s+,\\s*",",")
Upvotes: 7