Holay
Holay

Reputation: 5

How would it be possible to remove extra comma at the end of a string in java?

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.

Upvotes: 0

Views: 73

Answers (2)

Adabar94
Adabar94

Reputation: 19

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

Upvotes: -1

David Conrad
David Conrad

Reputation: 16359

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;
}

Upvotes: 2

Related Questions