Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove trailing comma from comma-separated string

Tags:

java

string

I got String from the database which have multiple commas (,) . I want to remove the last comma but I can't really find a simple way of doing it.

What I have: kushalhs, mayurvm, narendrabz,

What I want: kushalhs, mayurvm, narendrabz

like image 467
Kushal Shah Avatar asked Oct 18 '11 11:10

Kushal Shah


People also ask

How do you remove trailing commas from a string?

To remove the leading and trailing comma from a string, call the replace() method with the following regular expression as the first parameter - /(^,)|(,$)/g and an empty string as the second.

How do you remove spaces from a comma separated string in Java?

To remove extra spaces before and/or after the delimiter, we can perform split and trim using regex: String[] splitted = input. trim(). split("\\s*,\\s*");


11 Answers

To remove the ", " part which is immediately followed by end of string, you can do:

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

This handles the empty list (empty string) gracefully, as opposed to lastIndexOf / substring solutions which requires special treatment of such case.

Example code:

String str = "kushalhs, mayurvm, narendrabz, ";
str = str.replaceAll(", $", "");
System.out.println(str);  // prints "kushalhs, mayurvm, narendrabz"

NOTE: Since there has been some comments and suggested edits about the ", $" part: The expression should match the trailing part that you want to remove.

  • If your input looks like "a,b,c,", use ",$".
  • If your input looks like "a, b, c, ", use ", $".
  • If your input looks like "a , b , c , ", use " , $".

I think you get the point.

like image 197
aioobe Avatar answered Oct 02 '22 22:10

aioobe


You can use this:

String abc = "kushalhs , mayurvm , narendrabz ,";
String a = abc.substring(0, abc.lastIndexOf(","));
like image 29
srini Avatar answered Oct 02 '22 22:10

srini


Use Guava to normalize all your commas. Split the string up around the commas, throw out the empties, and connect it all back together. Two calls. No loops. Works the first time:

import com.google.common.base.Joiner;
import com.google.common.base.Splitter;

public class TestClass {

    Splitter splitter = Splitter.on(',').omitEmptyStrings().trimResults();
    Joiner joiner = Joiner.on(',').skipNulls();

    public String cleanUpCommas(String string) {
        return joiner.join(splitter.split(string));
    }

}



public class TestMain {

    public static void main(String[] args) {
        TestClass testClass = new TestClass();

        System.out.println(testClass.cleanUpCommas("a,b,c,d,e"));
        System.out.println(testClass.cleanUpCommas("a,b,c,d,e,,,,,"));
        System.out.println(testClass.cleanUpCommas("a,b,,, ,c,d,  ,,e,,,,,"));
        System.out.println(testClass.cleanUpCommas("a,b,c,d,  e,,,,,"));
        System.out.println(testClass.cleanUpCommas(",,, ,,,,a,b,c,d,  e,,,,,"));
    }

}

Output:

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

Personally, I hate futzing around with counting limits of substrings and all that nonsense.

like image 36
Steve J Avatar answered Oct 03 '22 00:10

Steve J


I'm late on this thread but hope it will help to some one.......

String abc = "kushalhs , mayurvm , narendrabz ,";

if(abc.indexOf(",") != -1){
    abc = abc.substring(0,abc.length() - 1);
}
like image 35
Yogesh Avatar answered Oct 02 '22 23:10

Yogesh


For more than one commas

            String names = "Hello,World,,,";
    System.out.println(names.replaceAll("(,)*$", ""));

Output: Hello,World

like image 38
Pandiarajan Avatar answered Oct 03 '22 00:10

Pandiarajan


(^(\s*?\,+)+\s?)|(^\s+)|(\s+$)|((\s*?\,+)+\s?$)

Regexr

ex:

a, b, c
, ,a, b, c, 
,a, b, c   ,
,,a, b, c, ,,,
, a, b, c,    ,
    a, b, c     
     a, b, c ,,
, a, b, c, 
, ,a, b, c, ,
 , a, b, c , 
,,, a, b, c,,, 
,,, ,,,a, b, c,,, ,,,
,,, ,,, a, b, c,,, ,,,
 ,,,a, b, c ,,,
 ,,,a, b, c,,, 
   a, b, c   

becomes:

a, b, c
a, b, c
a, b, c
a, b, c
a, b, c
a, b, c
a, b, c
a, b, c
a, b, c
a, b, c
a, b, c
a, b, c
a, b, c
a, b, c
a, b, c
a, b, c
like image 22
IceWarrior353 Avatar answered Oct 03 '22 00:10

IceWarrior353


And one more ... this also cleans internal commas mixed with whitespace:

From , , , ,one,,, , ,two three, , , ,,four, , , , , to one,two three, four

text.replaceAll("^(,|\\s)*|(,|\\s)*$", "").replaceAll("(\\,\\s*)+", ",");
like image 26
Christophe Roussy Avatar answered Oct 03 '22 00:10

Christophe Roussy


You can do something like using join function of String class.

import java.util.Arrays;
import java.util.List;

public class Demo {

    public static void main(String[] args) {
        List<String> items = Arrays.asList("Java", "Ruby", "Python", "C++");
        String output = String.join(",", items);
        System.out.println(output);
    }

}
like image 40
Rajesh Avatar answered Oct 03 '22 00:10

Rajesh


Check if str.charAt(str.length() -1) == ','. Then do str = str.substring(0, str.length()-1)

like image 29
Saurabh Avatar answered Oct 02 '22 22:10

Saurabh


This method is in BalusC's StringUtil class. his blog

i use it very often and will trim any string of any value:

/**
 * Trim the given string with the given trim value.
 * @param string The string to be trimmed.
 * @param trim The value to trim the given string off.
 * @return The trimmed string.
 */
public static String trim(String string, String trim) {
    if (string == null) {
        return null;
    }

    if (trim.length() == 0) {
        return string;
    }

    int start = 0;
    int end = string.length();
    int length = trim.length();

    while (start + length <= end && string.substring(
            start, start + length).equals(trim)) {
        start += length;
    }
    while (start + length <= end && string.substring(
            end - length, end).equals(trim)) {
        end -= length;
    }

    return string.substring(start, end);
}

ex:

trim("1, 2, 3, ", ", ");
like image 31
epoch Avatar answered Oct 02 '22 22:10

epoch


    String str = "kushalhs , mayurvm , narendrabz ,";
    System.out.println(str.replaceAll(",([^,]*)$", "$1"));
like image 33
Arkadiusz Cieśliński Avatar answered Oct 03 '22 00:10

Arkadiusz Cieśliński