justalazyguy
justalazyguy

Reputation: 49

Removing last comma every line

I am having trouble dealing with trailing commas in my code, I've tried one solution from this website but still couldn't solve it. Any help would be great.

Here's my code.

    String delimiter = "!@#$";
    for ( String data1: overall.keySet() )
    resultString += data1 + "," + overall.get(data1).toString() +  System.getProperty("line.separator");

    resultString = resultString.replace("," + delimiter , "");

Here's the one which I've found on this web, which only remove the last comma at the last line.

resultString += data1 + "," + overall.get(data1).toString() +  System.getProperty("line.separator");

resultString = resultString.replaceAll(",$", "");

My current output is

a,b,
c,d,
e,f,

Instead of

a,b
c,d
e,f

Upvotes: 0

Views: 4014

Answers (3)

TheLostMind
TheLostMind

Reputation: 36304

You have to use replaceAll() instead of replace() --> resultString = resultString.replaceAll(",$", ""); because replaceAll() takes regex where $ means end of input.

Example :

public static void main(String[] args) {
    String s = "abc,def,";
    System.out.println(s.replaceAll(",$", ""));
}

O/P :

abc,def

EDIT : Based on your code.

You should probably change your code to :

 for ( String data1: overall.keySet() ){
    resultString += data1 + "," + overall.get(data1).toString() +  System.getProperty("line.separator");
    resultString = resultString.replaceAll(",$", "");
}

Upvotes: 0

akhil_mittal
akhil_mittal

Reputation: 24157

If you simply want to remove trailing comma from a String having comma separated values you can try replaceAll:

String str = "a,b,c,d,e,f,";
str = str.replaceAll(",$", "");
System.out.println(str);

It prints: a,b,c,d,e,f

This solution also handles the empty list (empty string) gracefully, as opposed to lastIndexOf / substring solutions which requires special treatment of such case. In the above solution $ is a special symbol for matching the end of the string.

If you have an array of String then use it in a loop:

        String[] stringsArray = new String[] {"a,b", "c,d", "e,f"};
        for(String str : stringsArray) {
            str = str.replaceAll(",$", "");
            System.out.println(str);
        }

And output is:

a,b c,d e,f

Upvotes: 1

Ryan
Ryan

Reputation: 2084

You could remove the last character if every line as the comma:

resultString = resultString.substring(0, resultString.length()-1)

Upvotes: 1

Related Questions