重新格式化字符串数组

时间:2019-02-28 11:04:01

标签: java

我想根据条件重新格式化String数组。说,数组

A = ["samsung", "chargers", "fast", "charging", "rapid", "high"]

int index = 1

这意味着我将用空格将这些项附加到索引1,并格式化数组。因此,最后,它将是

A = ["samsung chargers", "fast", "charging", "rapid", "high"]

对于索引= 2,输出应为

A = ["samsung chargers fast", "charging", "rapid", "high"]

我编写了有效的代码,我试图找到更简洁(但不是低性能)的方法。

StringBuilder builder = null;

..........

int fCount = ...

// format the array to match the string
// values = ["samsung", "chargers", "fast", "charging", "rapid", "high"]

builder = new StringBuilder();
String formated = "";

for (int i = 0; i <= fCount; i++) {
    builder.append(values[i]).append(" ");
}

formated = builder.toString().trim();

String[] fVaues = new String[values.length - fCount];

fVaues[0] = formated;

for (int i = 1; i < fVaues.length; i++) {
    fVaues[i] = values[i+1];
}

完成它的简单方法是什么?

3 个答案:

答案 0 :(得分:4)

此方法执行相同的操作:

static String[] joinUntil(String[] original, int until) {
    return Stream.concat(
                Stream.of(String.join(" ", Arrays.copyOf(original, until))),
                Arrays.stream(Arrays.copyOfRange(original, until, original.length))
            ).toArray(String[]::new);
}

答案 1 :(得分:3)

private static List<String> reFormat(List<String> lst, int index){
    String joined = String.join(" ", lst.subList(0, index + 1));
    List<String> res = new ArrayList<String>();
    res.add(joined);
    res.addAll(lst.subList(index + 1, lst.size()));
    return res;
}

答案 2 :(得分:2)

您可以遍历它,将字符串添加到第二个数组:

String[] b = new String[a.length - index];
String tmp = a[0];

for(int i = 1; i < a.length; i++) {
    if(i <= index) {
        tmp += " " + a[i];

        if(i == index) {
            b[i - index] = tmp;
        }
    }
    else {
        b[i - index] = a[i];
    }
}