patternjavaCritical
Remove Last Comma
Viewed 0 times
removelastcomma
Problem
I want to join strings together, but when doing this it often happens that there is a comma too many, and therefore I need to remove that comma. In this code, I use the
How can this become more elegant?
substring to delete the two last characters.How can this become more elegant?
List paramList = new ArrayList( );
paramList.add( "param1" );
paramList.add( "param2" );
StringBuilder result = new StringBuilder();
for ( String p : paramList )
{
result.append( p ).append( ", " );
}
String withoutLastComma = result.substring( 0, result.length( ) - ", ".length( ) );
System.err.println( withoutLastComma );Solution
One may use string utility methods such as
For example:
StringUtil.join to concatenate elements in an array or a collection object. Consult the StringUtil API's StringUtil.join entry.For example:
StringUtils.join(["a", "b", "c"], "--") // => "a--b--c"Code Snippets
StringUtils.join(["a", "b", "c"], "--") // => "a--b--c"Context
StackExchange Code Review Q#1973, answer score: 135
Revisions (0)
No revisions yet.