-2

我有一个String [] Names包含几个像这样的值

[Alex Jones, Robert Flip, Farabi Fahim]

现在,我的问题是

1)现在,我想用最后一个字符之前的替换最后","一个&[这里是 Farabi Fahim]。我怎么做 ?

输出会像

[Alex Jones, Robert Flip & Farabi Fahim]

2)最快、最有效和推荐的方法是什么?

4

6 回答 6

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]
于 2013-07-16T20:24:28.033 回答
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();
于 2013-07-16T20:21:11.630 回答
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 out = Arrays.toString(s2);
于 2013-07-16T20:25:23.030 回答
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];
于 2013-07-16T20:26:00.783 回答
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]);
    }
于 2013-07-16T20:28:20.150 回答
-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;
}

这应该可以解决问题。

于 2013-07-16T20:22:10.233 回答