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.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…