我有一个String [] Names
,其中包含几个像这样的值
[Alex Jones, Robert Flip, Farabi Fahim]
现在,我的问题是
1)现在,我想在最后一个角色[这里是Farabi Fahim]之前用","
替换最后&
。我该怎么做?
输出就像
[Alex Jones, Robert Flip & Farabi Fahim]
2)最快,最有效,最推荐的方法是什么?
答案 0 :(得分:3)
这应该有效:
String[] arr = new String[] {"Alex Jones", "Robert Flip", "Farabi Fahim"};
StringBuilder sbd = new StringBuilder("[");
for (int i = 0; i < arr.length; i++) {
sbd.append(arr[i]);
if (i < arr.length - 2)
sbd.append(", ");
else if (i < arr.length - 1)
sbd.append(" & ");
}
sbd.append(']');
System.out.printf("%s%n", sbd);
String output = Arrays.toString(arr).replaceAll(", (?=[^,]*$)", " & ")
<强>输出:强>
[Alex Jones, Robert Flip & Farabi Fahim]
答案 1 :(得分:1)
在这种情况下,您将字符串数组转换为单个字符串(看起来您的第一个语句的输出只是使用toString
方法。最简单的方法是for
循环:
String str = arr[0];
for (int i = 1; i < (arr.length - 1); i++) {
str += (", " + arr[i]);
}
str += (" & " + arr[arr.length - 1]);
或者,如果您想要真正提高效率,可以使用StringBuilder
类来构建字符串:
StringBuilder strBuilder = new StringBuilder(arr[0]);
for (int i = 1; i < (arr.length - 1); i++) {
strBuilder.append(", ");
strBuilder.append(arr[i]);
}
strBuilder.append(" & ");
strBuilder.append(arr[arr.length - 1]);
String str = strBuilder.toString();
答案 2 :(得分:0)
假设:
String[] s1 = new String[] {"Alex Jones", "Robert Flip", "Farabi Fahim"};
这样做:
String[] s2 = new String[] {s1[0], s1[1] + " & " + s1[2]};
更一般地说(省略完整性检查):
String[] s2 = new String[s1.length - 1];
System.arraycopy(s1, 0, s2, 0, s2.length);
s2[s2.length - 1] += " & " + s1[s1.length - 1];
如果您希望输出为String而不是String数组,请添加以下行:
String out = Arrays.toString(s2);
答案 3 :(得分:0)
你走了。下次发布一些自己的代码。
// create new array that is one element shorter, i.e. [Alex,Robert]
String[] newnames = Array.copyOf(names, names.length-1);
// attach the formerly last element to the new last element
newnames[newnames.length-1] = newnames[newnames.length-1] + "&" + names[names.length-1];
答案 4 :(得分:0)
我建议快速循环打印:
for(int i = 0; i < names.length; i++){
if(i == names.length - 2)
System.out.print(names[i] + " & ");
else if(i < names.length - 1)
System.out.print(names[i] + ", ");
else
System.out.print(names[i]);
}
答案 5 :(得分:-1)
public String addAnd(String[] s)
{
String result = "";
for (int i = 0; i < s.length - 2; i++)
{
result += s[i] + ", "
}
result += s[s.length - 2];
result += (" & " + s[s.length - 1]);
return result;
}
这应该可以解决问题。