Jeetendra Ahuja Jeetendra Ahuja - 1 year ago 64
Java Question

StringBuilder append "," basic concern

I have a code like:

projsForWhichPermCheckFailedSBuilder.append(currentProject.getDisplayString()).append(", ");

This is dynamic append and above code is in for loop... so at last I want to remove extra ", ", I have done something like:

projsForWhichPermCheckFailedString = projsForWhichPermCheckFailedSBuilder.substring(0, projsForWhichPermCheckFailedSBuilder.length()-2);

Please suggest some better way!!! Thanks...

Answer Source

Assuming we are in .NET, If you are appending data separated by a pre-defined delimiter, you can first build your delimited-valued string, using

//choosing "," as the delimiter
//strs -> is a IEnumerable<string> you build within your loop 
string s = string.Join(",", strs);

With the approach above, you are rid of having to remove the last delimiter added...

the result, you can finally append to your string builder instance: