Remove trailing comma from comma-separated string

JavaString

Java Problem Overview


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

Java Solutions


Solution 1 - Java

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.

Solution 2 - Java

You can use this:

String abc = "kushalhs , mayurvm , narendrabz ,";
String a = abc.substring(0, abc.lastIndexOf(","));

Solution 3 - Java

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.

Solution 4 - Java

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

Solution 5 - Java

For more than one commas

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

Output: Hello,World

Solution 6 - Java

(^(\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

Solution 7 - Java

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*)+", ",");

Solution 8 - Java

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

}

Solution 9 - Java

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

Solution 10 - Java

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, ", ", ");

Solution 11 - Java

    String str = "kushalhs , mayurvm , narendrabz ,";
    System.out.println(str.replaceAll(",([^,]*)$", "$1"));

Solution 12 - Java

You can do something like this using 'Java 8'

private static void appendNamesWithComma() {
	List<String> namesList = Arrays.asList("test1", "tester2", "testers3", "t4");
	System.out.println(namesList.stream()
								.collect(Collectors.joining(", ")));

}

Solution 13 - Java

You can try with this, it worked for me:

if (names.endsWith(",")) {
    names = names.substring(0, names.length() - 1);
}

Or you can try with this too:

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

Solution 14 - Java

public static String removeExtraCommas(String entry) {
	if(entry==null)
		return null;
	
	String ret="";
	entry=entry.replaceAll("\\s","");
	String arr[]=entry.split(",");
	boolean start=true;
	for(String str:arr) {
		if(!"".equalsIgnoreCase(str)) {
			if(start) {
				ret=str;
				start=false;
			}
			else {
			ret=ret+","+str;
			}
		}
	}				
	return ret;
	
}

Solution 15 - Java

i am sharing code form my project using regular expression you can do this...

String ChildBelowList = "";

    if (!Childbelow.isEmpty()) {
        for (int iCB = 0; iCB < Childbelow.size(); iCB++) {

            ChildBelowList = ChildBelowList += Childbelow.get(iCB) + ",";



        }
        ChildBelowList = ChildBelowList.replaceAll("(^(\\s*?\\,+)+\\s?)|(^\\s+)|(\\s+$)|((\\s*?\\,+)+\\s?$)", "");

        tv_childbelow.setText(ChildBelowList);

    } else {
        ll_childbelow.setVisibility(View.GONE);
    }

Solution 16 - Java

Or something like this:

private static String myRemComa(String input) {	
		String[] exploded = input.split(",");
		input="";
		boolean start = true;
		for(String str : exploded) {
			
		 str=str.trim();
		 if (str.length()>0) {
			 if (start) {
				 input = str;
					start = false;
				} else {
					input = input + "," + str;
				}
		 }
		}
		
		return input;
	}

Solution 17 - Java

package com.app;

public class SiftNumberAndEvenNumber {

	public static void main(String[] args) {

		int arr[] = {1,2,3,4,5};
		int arr1[] = new int[arr.length];
		int shiftAmount=3;
		
		for(int i = 0; i < arr.length; i++){
			int newLocation = (i + (arr.length - shiftAmount)) % arr.length;
			arr1[newLocation] = arr[i];
			
		}
		for(int i=0;i<arr1.length;i++) {
			if(i==arr1.length-1) {
				System.out.print(arr1[i]);
			}else {
				System.out.print(arr1[i]+",");
			}
		}
		System.out.println();
		for(int i=0;i<arr1.length;i++) {
			if(arr1[i]%2==0) {
				System.out.print(arr1[i]+" ");
			}
		}
	}
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionKushal ShahView Question on Stackoverflow
Solution 1 - JavaaioobeView Answer on Stackoverflow
Solution 2 - JavasriniView Answer on Stackoverflow
Solution 3 - JavaSteve JView Answer on Stackoverflow
Solution 4 - JavaYogeshView Answer on Stackoverflow
Solution 5 - JavaPandiarajanView Answer on Stackoverflow
Solution 6 - JavaIceWarrior353View Answer on Stackoverflow
Solution 7 - JavaChristophe RoussyView Answer on Stackoverflow
Solution 8 - JavaRajeshView Answer on Stackoverflow
Solution 9 - JavaSaurabhView Answer on Stackoverflow
Solution 10 - JavaepochView Answer on Stackoverflow
Solution 11 - JavaArkadiusz CieślińskiView Answer on Stackoverflow
Solution 12 - JavaDamien-AmenView Answer on Stackoverflow
Solution 13 - JavaTarit RayView Answer on Stackoverflow
Solution 14 - JavablathurView Answer on Stackoverflow
Solution 15 - JavaHitesh KushwahView Answer on Stackoverflow
Solution 16 - JavacrezesView Answer on Stackoverflow
Solution 17 - JavaVenkatView Answer on Stackoverflow