Remove trailing comma from comma-separated string

前端 未结 16 892
生来不讨喜
生来不讨喜 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: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, ", ", ");
    

提交回复
热议问题