如何在Java中将2个或多个字符串连接成一个字符串数组中的一个字符串?

9
我希望能够将两个或多个连续的字符串按照两个变量x和y中的规定合并成一个字符串数组,其中x表示从第x个元素开始,一直合并到连续的y个元素结束。例如,如果一个名为'A'的数组有以下元素:
A = {"europe", "france", "germany", "america"};
x=2;y=2;
//Here, I want to concatenate france and germany as :
A = {"europe", "france germany", "america"};
//Or 
x=2,y=3;

A= {"europe", "france germany america"};

就像这样。有人知道如何在不涉及复杂编程的情况下完成这个吗?


我不理解xy值如何转换为各种连接。 - Tim Biegeleisen
是的,这正是我在想的事情。 - AshAR
在数组@TimBiegeleisen中,我想要将特定的连续单词连接起来(根据需求,起始单词和要连接的单词数会发生变化)。这就是为什么需要x(数组中第一个单词的位置)和y(要连接的单词数)。我希望它们可以在for循环中使用。 - Dante
  1. 创建一个正确长度的数组。
  2. 使用 System.arraycopy 将数组前后的元素复制到数组中。
  3. 使用 String.join 连接中间的元素。
- Andy Turner
@AndyTurner 你可以把它作为答案发布,因为这可能是最有效的方法 :-) - Tim Biegeleisen
显示剩余3条评论
8个回答

6

可能最简洁的方法是:

  1. Construct an array of the right size:

    String[] result = new String[A.length - (y-1)];
    
  2. Copy the start and the end of the array using System.arraycopy:

    System.arraycopy(A, 0, result, 0, x-1);
    System.arraycopy(A, x+y-1, result, x+1, A.length-(x+1));
    
  3. Build the concatenated string:

    result[x-1] = String.join(" ", Arrays.asList(A).subList(x-1, x-1+y));
    
(注:由于写作日期的原因,可能存在一些偏差)

2

这里有一个可行的脚本,虽然我不知道你是否认为它足够简单。该算法是简单地遍历输入数组,将字符串复制到输出中,直到我们到达由x值确定的第一个条目。然后,我们将y个术语连接成一个字符串。最后,我们通过逐一复制剩余的术语来完成。

public static String[] concatenate(String[] input, int x, int y) {
    List<String> list = new ArrayList<>();
    // just copy over values less than start of x range
    for (int i=0; i < x-1; ++i) {
        list.add(input[i]);
    }

    // concatenate y values into a single string
    StringBuilder sb = new StringBuilder("");
    for (int i=0; i < y; ++i) {
        if (i > 0) sb.append(" ");
        sb.append(input[x-1+i]);
    }
    list.add(sb.toString());

    // copy over remaining values
    for (int i=x+y-1; i < input.length; ++i) {
        list.add(input[i]);
    }
    String[] output = new String[list.size()];
    output = list.toArray(output);

    return output;
}

String[] input = new String[] {"europe", "france", "germany", "america"};
int x = 2;
int y = 3;
String[] output = concatenate(input, x, y);
for (String str : output) {
    System.out.println(str);
}

Demo


1

这里有一个非常直接的过程方法:

private static ArrayList<String> concatenate(String[] strings, int x, int y) {
    ArrayList<String> retVal = new ArrayList<>();
    StringBuilder builder = new StringBuilder();
    int count = y;
    boolean concatenated = false;
    for (int i = 0 ; i < strings.length ; i++) {
        if (i < x - 1 || concatenated) {
            retVal.add(strings[i]);
        } else {
            builder.append(" ");
            builder.append(strings[i]);
            count--;
            if (count == 0) {
                retVal.add(builder.toString());
                concatenated = true;
            }
        }
    }
    return retVal;
}

解释:

  • 对于输入数组中的每个元素:
  • 如果我们还没有到达索引为x - 1,或者我们已经完成了拼接,则将元素添加到返回值中。
  • 如果我们到达了x - 1,但是尚未完成拼接,则将该元素添加到字符串生成器中。
  • 如果我们完成了拼接(由count == 0表示),则将拼接后的字符串添加到返回值中。

1
使用for循环并跟踪索引来完成。
String[] A = {"europe", "france", "germany", "america"};

String[] new_Array;
// your code goes here
int x=2,y=3;
int start_concat = x-1 ; // to account for array index

int stop_concat = start_concat+y;

new_Array = new String[A.length-y + 1];

for(int i=0; i<=start_concat; i++){   
     new_Array[i] = A[i];
}

for(int i = start_concat+1 ; i<stop_concat; i++){
    new_Array[start_concat] = new_Array[start_concat] + A[i];
}

for(int i =start_concat+1, j=stop_concat ; i< new_Array.length;i++,j++){
    new_Array[i] = A[j];
}

for(int i=0; i<new_Array.length; i++){
    System.out.println(new_Array[i]);
}

在ideone上查看我的代码片段


1
使用List API,我们可以利用subList方法和addAll方法修改列表的特定部分,并在指定位置插入元素。
除此之外,我们还使用String replace方法来删除列表的冗余字符串表示,并最终将累加器列表转换为字符串数组。
public static String[] concatElements(String[] elements, int start, int count){

       List<String>  accumulator = new ArrayList<>(Arrays.asList(elements));
       List<String> subList = new ArrayList<>(accumulator.subList(--start, start + count));
       accumulator.removeAll(subList);

       String concatenatedElements = subList.toString()
                      .replace(",", "")
                      .replace("[","")
                      .replace("]", "");

       subList = Collections.singletonList(concatenatedElements);
       accumulator.addAll(start, subList);
       String[] resultSet = new String[accumulator.size()];

       for (int i = 0; i < accumulator.size(); i++) {
            resultSet [i] = accumulator.get(i);
       }
       return resultSet;
}

这句话的意思是:这样调用它:
System.out.println(Arrays.toString(concatElements(array, 2, 2)));

将会产生:
[europe, france germany, america]

并这样调用它:
System.out.println(Arrays.toString(concatElements(array, 2, 3)));

将产生:

[europe, france germany america]

目前代码中没有对参数 startcount 进行验证,但我将其留作练习题。


1
可能使用列表实现。
public static void main(String[] args) {
    String arr []= {"europe", "france", "germany", "america"};
    int from =1;
    int toAdd =3;
    int len = arr.length;

    if(from+toAdd>len){
        //show error
        return ;
    }
    List<String> list = Arrays.asList(arr);
    List<String> concatList = list.subList(from, from+toAdd);
    StringBuilder sb = new StringBuilder();
    for(String st: concatList){
        sb.append(st).append(" ");
    }
    List<String>outList = new ArrayList<>(list.subList(0, from));
    outList.add(sb.toString());
    if(from+toAdd<len-1){
        outList.addAll(list.subList(from+toAdd, list.size()-1));
    }
    System.out.println(outList);
}

0

在Android中连接字符串,我们可以使用TextUtils.copyOfRange()类。对于其余部分,我们可以使用System.arraycopy()方法来避免循环:

public static String[] concatenate(String[] input,
                                   int from, // starts from 0 position
                                   int number){
    String[] res = new String[input.length - number + 1];

    int to = from + number;

    System.arraycopy(input, 0, res, 0, from);

    String[] sub = Arrays.copyOfRange(input, from, to);
    String joined = TextUtils.join(" ", sub);
    res[from] = joined;

    System.arraycopy(input, to, res, from + 1, input.length - to);

    return res;
}

我认为将要连接的字符串复制到另一个数组中,并将连接后的字符串添加回原始数组是个好主意。但是,尽管这种方法不使用任何循环,它会使用额外的字符串数组。我猜除非可以完全删除数组的元素(而不仅仅是将它们设置为空),否则我需要的功能是不可能实现的。 - Dante

0

使用java.util.stream库的另一种选择:

这里使用IntStream.range来确定输出List的新大小,并生成代表输出序列中索引的int

然后,对于每个输出索引,使用.mapToObj来决定要放置在每个相应位置上的内容(输出仅具有连接字符串的单个索引)。

对于输出,基本上有3种可能性-由getOrMergeData方法决定:

  • 连接字符串的索引之前-使用data[index]
  • 连接字符串的索引之后-使用data[index + count - 1]
  • 在连接字符串的索引处-使用Arrays.copyOfRangestring.Join将需要合并在一起的字符串连接在一起。

点击查看运行示例:

class Main {
  public static void main(String[] args) {
    String [] data = {"europe", "france", "germany", "america"};
    int startIndex = 1;
    int count = 2;
    int newSize = data.length - count + 1;

    List<String> output =
        IntStream.range(0, newSize)
                 .mapToObj(n -> Main.getOrJoin(data, startIndex, count, n))
                 .collect(Collectors.toList());

    for (String s : output) {
      System.out.println(s);
    }
  }

  private static String getOrJoin(String[] data, int joinIndex, int count, int index) {
    if (index < joinIndex) return data[index];
    else if (index > joinIndex) return data[index + count - 1];
    else {
        String[] dataToJoin = Arrays.copyOfRange(data, joinIndex, joinIndex + count);
        return String.join(" ", dataToJoin);
    }
  }
}

输出:

europe
france germany
america

也许只是我的Java知识水平有限,但这看起来有点复杂。 - Dante

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接