合并字符串数组的实现
看源代码:
import Java . util . ArrayList;
导入Java . util . arrays;
导入Java . util . list;
/**
*合并多个字符串数组。
*
* www . exmoda . com
*/
class T {
public static void main(String[]args){
String[]S1 = { " 1 "," 2 " };
String[] s2 = { "3 "," 4 " };
String[] s3 =新字符串[S1 . length+S2 . length];
System.arraycopy(s1,0,s3,0,S1 . length);
System.arraycopy(s2,0,s3,s1.length,S2 . length);
system . out . println(arrays . tostring(S3));
//方法2,使用list
list list = new ArrayList();
for(String s:S1){
list . add(s);
}
for(String s:S2){
list . add(s);
}
String[]S4 = list . to array(new String[0]);
system . out . println(arrays . tostring(S4));
}
}
原理很简单。创建一个可以容纳所有数据的新数组,然后根据其长度进行复制。
0条评论