编写一个接受String[]
数组并返回一个新数组的方法,原始数组重复两次。
例如:
repeatArray(new String[]{"a", "b", "c"})
应该返回一个包含以下元素的新数组:
["a", "b", "c", "a", "b", "c"]
您可以通过使用System.arraycopy来做到这一点,如下所示:
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
// Test printing the result
System.out.println(Arrays.toString(repeatArray(new String[] { "a", "b", "c" })));
// Also, test assigning the result to another array
String[] result = repeatArray(new String[] { "a", "b", "c" });
System.out.println(Arrays.toString(result));
}
static String[] repeatArray(String[] array) {
String[] result = new String[array.length * 2];
System.arraycopy(array, 0, result, 0, array.length);
System.arraycopy(array, 0, result, array.length, array.length);
return result;
}
}
输出:
[a, b, c, a, b, c]
[a, b, c, a, b, c]
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句