Remove trailing comma from comma-separated string

前端 未结 16 885
生来不讨喜
生来不讨喜 2020-12-04 21:37

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.

相关标签:
16条回答
  • 2020-12-04 22:02

    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);
        }
    
    }
    
    0 讨论(0)
  • 2020-12-04 22:03

    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, ", ", ");
    
    0 讨论(0)
  • 2020-12-04 22:04

    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;
        }
    
    0 讨论(0)
  • 2020-12-04 22:05

    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(", $", "");
    
    0 讨论(0)
提交回复
热议问题