Remove trailing comma from comma-separated string

前端 未结 16 917
生来不讨喜
生来不讨喜 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 21:38

    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.

提交回复
热议问题