从逗号分隔的字符串中移除末尾逗号

66

我从数据库中获取了一个带有多个逗号(,)的字符串。我想要删除最后一个逗号,但我找不到一个简单的方法来实现它。

现在的样子:kushalhs, mayurvm, narendrabz,

想要得到的结果:kushalhs, mayurvm, narendrabz


1
阅读java.lang.String的javadoc。它包含了你所需的所有方法。http://download.oracle.com/javase/6/docs/api/ - JB Nizet
17个回答

163

要删除紧跟在字符串结尾处的", "部分,您可以执行以下操作:

str = str.replaceAll(", $", "");

与使用lastIndexOf / substring的解决方案需要对空列表(空字符串)进行特殊处理相比,此方法优雅地处理空列表。

示例代码:

String str = "kushalhs, mayurvm, narendrabz, ";
str = str.replaceAll(", $", "");
System.out.println(str);  // prints "kushalhs, mayurvm, narendrabz"

注意:由于一些评论和建议编辑关于", $"部分的表达式应该匹配你想要删除的尾部部分。

  • 如果你的输入看起来像"a,b,c,",那么使用",$"
  • 如果你的输入看起来像"a, b, c, ",那么使用", $"
  • 如果你的输入看起来像"a , b , c , ",那么使用" , $"

我觉得你已经明白了。


$ 的作用是什么?它代表了最后一个索引吗? - Harinder
不完全是“最后匹配”。它是用于匹配字符串结尾的特殊符号。 - aioobe
2
str.replaceAll(",$",""); 无法移除最后一个逗号。你需要在逗号和美元符号之间添加一个空格才能使其正常工作:str.replaceAll(", $","");。截至Java 7.0版本已测试通过。 - Lemmings19
4
@Lemmings19,当然取决于您从哪个字符串开始。它确实从OP提供的示例字符串中删除了它,不是吗?为了更加通用,可以使用正则表达式\s*,\s*$ - aioobe
@aioobe 啊...我想通了。> <我有一个尾随的空格,我没有看到它。现在一切都有意义了。昨晚肯定不行!人为错误。我的脑子转不过来。您提供的正则表达式有效,就像应该的那样。 - Lemmings19

12

你可以使用这个:

String abc = "kushalhs , mayurvm , narendrabz ,";
String a = abc.substring(0, abc.lastIndexOf(","));

1
这有点危险:如果你使用 abc = "kushalhs,mayurvm,narendrabz",那么结果会是 "kushalhs,mayurvm"。 - Linus

9

使用Guava来规范化所有逗号。将字符串分割成逗号周围的部分,丢弃空白,并重新连接所有内容。两次调用。无循环。第一次即可运行:

import com.google.common.base.Joiner;
import com.google.common.base.Splitter;

public class TestClass {

    Splitter splitter = Splitter.on(',').omitEmptyStrings().trimResults();
    Joiner joiner = Joiner.on(',').skipNulls();

    public String cleanUpCommas(String string) {
        return joiner.join(splitter.split(string));
    }

}



public class TestMain {

    public static void main(String[] args) {
        TestClass testClass = new TestClass();

        System.out.println(testClass.cleanUpCommas("a,b,c,d,e"));
        System.out.println(testClass.cleanUpCommas("a,b,c,d,e,,,,,"));
        System.out.println(testClass.cleanUpCommas("a,b,,, ,c,d,  ,,e,,,,,"));
        System.out.println(testClass.cleanUpCommas("a,b,c,d,  e,,,,,"));
        System.out.println(testClass.cleanUpCommas(",,, ,,,,a,b,c,d,  e,,,,,"));
    }

}

输出:

a,b,c,d,e
a,b,c,d,e
a,b,c,d,e
a,b,c,d,e
a,b,c,d,e

个人而言,我讨厌在计算子字符串的限制和所有那些无聊的东西上浪费时间。


3
你可以使用String类的join函数来完成此操作。
import java.util.Arrays;
import java.util.List;

public class Demo {

    public static void main(String[] args) {
        List<String> items = Arrays.asList("Java", "Ruby", "Python", "C++");
        String output = String.join(",", items);
        System.out.println(output);
    }

}

3

虽然我来晚了,但希望这篇文章能对某些人有所帮助……

String abc = "kushalhs , mayurvm , narendrabz ,";

if(abc.indexOf(",") != -1){
    abc = abc.substring(0,abc.length() - 1);
}

3

针对超过一个逗号的情况

            String names = "Hello,World,,,";
    System.out.println(names.replaceAll("(,)*$", ""));

输出: 你好,世界


3

还有一个功能...可以清除与空格混合的内部逗号:

, , , ,one,,, , ,two three, , , ,,four, , , , ,one,two three, four

text.replaceAll("^(,|\\s)*|(,|\\s)*$", "").replaceAll("(\\,\\s*)+", ",");

3
(^(\s*?\,+)+\s?)|(^\s+)|(\s+$)|((\s*?\,+)+\s?$)

Regexr

例子:

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   

成为:

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

2

检查是否有 str.charAt(str.length() -1) == ',', 如果是,则执行 str = str.substring(0, str.length()-1)


在空字符串上中断(StringIndexOutOfBoundsException - aioobe
这些是边界条件,我认为你已经在处理了。就像你函数的第一行应该检查if(string == null || string.trim().equals("")) return; - Saurabh

1

这个方法在BalusC的StringUtil类中。他的博客

我经常使用它,可以修剪任何值的任何字符串:

/**
 * 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);
}

例子:

trim("1, 2, 3, ", ", ");

1
这将从实际值中删除前导的 ", " ;-) - aioobe

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接