Java删除最后一个字符串

时间:2013-08-07 07:01:46

标签: java stringbuilder

我有不同类型的名字。喜欢

ABC BCD, EFG HGF, HGF HJK

我想将,替换为"and"。所以,格式将是这样的

ABC BCD, EFG HGF & HGF HJK

我试过这个

names = "Jon Benda, Jon Wetchler, Thomas Leibig "
StringBuilder sbd = new StringBuilder();
String[] n = getNames.split("\\s+");
System.out.println(n.length);
for (int i = 0; i < n.length; i++) {
    sbd.append(n[i]);
    System.out.print(n[i]);
    if (i < n.length - 3)
        sbd.append(" ");
    else if (i < n.length - 2)
        sbd.append(" & ");
}
System.out.print("\n");
System.out.print(sbd);

6 个答案:

答案 0 :(得分:23)

为什么要过度复杂化?您可以使用String#lastIndexOf搜索,的最后一个索引,然后使用StringBuilder#replace

int lastIdx = names.lastIndexOf(",");
names = new StringBuilder(names).replace(lastIdx, lastIdx+1, "and").toString();

答案 1 :(得分:5)

你可以这样做。

 public static void main(String[] args) {
        String names = "Jon Benda, Jon Wetchler, Thomas Leibig ";
        String newNames = "";
        StringBuilder sbd = new StringBuilder();
        String[] n = names.split(",");
        System.out.println(n.length);
        for (int i = 0; i < n.length; i++) {

            if (i == n.length - 1) {
                newNames = newNames + " and " + n[i];
            } else {
                newNames = newNames + n[i] + " ";
            }
        }
        System.out.println(newNames);
    }

此输出

 Jon Benda  Jon Wetchler  and  Thomas Leibig 

答案 2 :(得分:4)

你必须使用RegEx吗?

怎么样:

int lastIndexOfComa = getNames.lastIndexOf(",");
names = getNames.substring(0, lastIndexOfComa) + " &" + getNames.substring(lastIndexOfComa, getNames.length);

答案 3 :(得分:3)

试试这个

 String name = "ABC BCD, EFG HGF, HGF HJK";
    int index=name.lastIndexOf(",");
    StringBuilder sb=new StringBuilder();
    sb.append(name.substring(0,index));
    sb.append(" and ");
    sb.append(name.substring(index+1,name.length()));
    System.out.println(sb);

答案 4 :(得分:0)

一个班轮:

name=name.replace(name.substring(name.lastIndexOf(",")),"&"+name.substring(name.lastIndexOf(",")+1))

答案 5 :(得分:0)

已经回答,但这是我的贡献:

String name = "ABC BCD, EFG HGF, HGF HJK";    
name = name.replaceFirst("(.*),", "$1 &")

在这种情况下,使用replaceFirst和replaceAll是一样的,所以正则表达式只匹配一次。