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.
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.
"a,b,c,"
, use ",$"
."a, b, c, "
, use ", $"
."a , b , c , "
, use " , $"
.I think you get the point.
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(", ")));
}
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);
}
Check if
str.charAt(str.length() -1) == ','
.
Then do
str = str.substring(0, str.length()-1)
(^(\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
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);
}