从逗号分隔的字符串中删除尾随逗号 [英] Remove trailing comma from comma-separated string
问题描述
我从数据库中获得了多个逗号(,
)的字符串。我想删除最后一个逗号,但我找不到一个简单的方法。
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.
我拥有的: kushalhs,mayurvm,narendrabz,
我想要的是什么: kushalhs,mayurvm,narendrabz
推荐答案
删除,
部分紧跟着字符串结尾,你可以这样做:
To remove the ", "
part which is immediately followed by end of string, you can do:
str = str.replaceAll(", $", "");
它优雅地处理空列表(空字符串),而不是 lastIndexOf
/ substring
需要特殊处理此类案例的解决方案。
This handles the empty list (empty string) gracefully, as opposed to lastIndexOf
/ substring
solutions which requires special treatment of such case.
示例代码:
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,
,使用,$
。 - 如果您的输入看起来像
a,b,c,
,使用,$
。 - 如果您的输入看起来像
a,b,c,
,使用,$
。
- 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" , $"
.
我认为你明白了。
这篇关于从逗号分隔的字符串中删除尾随逗号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!