java 多个String数组合并
时间: 2023-11-22 07:07:49 浏览: 79
可以使用Java的Arrays类中的copyOf()和System.arraycopy()方法来合并多个String数组。
方法1:使用copyOf()方法
```java
String[] arr1 = {"Java", "is", "cool"};
String[] arr2 = {"I", "love", "it"};
String[] arr3 = {"How", "about", "you?"};
// 计算新数组的长度
int totalLength = arr1.length + arr2.length + arr3.length;
// 创建新数组
String[] result = Arrays.copyOf(arr1, totalLength);
// 将arr2和arr3合并到result中
System.arraycopy(arr2, 0, result, arr1.length, arr2.length);
System.arraycopy(arr3, 0, result, arr1.length + arr2.length, arr3.length);
System.out.println(Arrays.toString(result)); // [Java, is, cool, I, love, it, How, about, you?]
```
方法2:使用System.arraycopy()方法
```java
String[] arr1 = {"Java", "is", "cool"};
String[] arr2 = {"I", "love", "it"};
String[] arr3 = {"How", "about", "you?"};
// 计算新数组的长度
int totalLength = arr1.length + arr2.length + arr3.length;
// 创建新数组
String[] result = new String[totalLength];
// 将arr1、arr2和arr3合并到result中
System.arraycopy(arr1, 0, result, 0, arr1.length);
System.arraycopy(arr2, 0, result, arr1.length, arr2.length);
System.arraycopy(arr3, 0, result, arr1.length + arr2.length, arr3.length);
System.out.println(Arrays.toString(result)); // [Java, is, cool, I, love, it, How, about, you?]
```
上述两种方法都可以实现多个String数组的合并。需要注意的是,第一种方法使用了Arrays.copyOf()方法创建新数组,而第二种方法则直接使用了new关键字创建了一个新的数组。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)