Trailing commas are a pretty common issue on contest problems. What happens is you find yourself iterating through a loop, tacking on a value from an array or list followed by a comma. And it works perfectly up until the end when you wind up with an extra comma at the end.
I’ve seen students use
substring to chop off the last two elements of the string, and that works okay. But I like this solution a little more.
What we’re doing is setting up a regex replacement that strips out any number of spaces, followed by any number of commas, followed by any number of spaces at the end of the string and then replaces it with an empty string.
\s is any whitespace (the two \ is because you have to escape the back slash). The
* after tells the match to match any number of the previous element, including zero. Same thing with
,* and the second
\\s*. The regex string ends with
$ which is the end of the string, so it will only match the last comma.
Depending on the problem, there may be an easier way with Java 8 using the String join method.
Let’s say you have an
ArrayList filled with strings that you want to separate with commas.
This keeps you from having to iterate through the list. You just send it into the join method and you’re done.
Want to stay in touch and keep up to date with the latest posts @ CompSci.rocks?