7

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

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);
4

6 回答 6

23

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

int lastIdx = names.lastIndexOf(",");
names = new StringBuilder(names).replace(lastIdx, lastIdx+1, "and").toString();
于 2013-08-07T07:05:02.150 回答
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 
于 2013-08-07T07:10:37.977 回答
4

你必须使用正则表达式吗?

关于什么:

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

?

于 2013-08-07T07:08:16.937 回答
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);
于 2013-08-07T07:07:18.507 回答
0

一个班轮:

name=name.replace(name.substring(name.lastIndexOf(",")),"&"+name.substring(name.lastIndexOf(",")+1))
于 2013-08-07T07:38:09.993 回答
0

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

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

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

于 2015-11-22T08:51:19.993 回答