我有不同类型的名字。喜欢
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);
最佳答案
为什么要把它复杂化?您可以使用 String#lastIndexOf
搜索 ,
的最后一个索引然后使用 StringBuilder#replace
:
int lastIdx = names.lastIndexOf(",");
names = new StringBuilder(names).replace(lastIdx, lastIdx+1, "and").toString();
关于Java删除最后一个字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18096698/