public Image addComments(String createComments) {
comments.append(createComments ",");
return this;
}
This is what I get, A,B,
This is how I want it to be: A,B
I tried using a regular expression
createComments = createComments.replaceAll(",$", "");
But It didn't work.
CodePudding user response:
If comments
is a StringBuilder
(or StringBuffer
) you can avoid adding a trailing comma:
public Image addComments(String createComments) {
if (comments.length() > 0) comments.append(",");
comments.append(createComments);
return this;
}
CodePudding user response:
I think you can avoid this whole comma situation with use of any Collection and String.join
Collection<String> comments = Arrays.asList("A", "B", "C", "D");
final String joinedComments = String.join(",", comments);
System.out.println(joinedComments);
This will return
A,B,C,D