[英]Java string[] partial copying
如何获取String[]
,并复制该String[]
,但没有第一个String? 示例:如果我有这个......
String[] colors = {"Red", "Orange", "Yellow"};
我如何制作一个新的字符串,就像字符串集合颜色,但没有红色?
你可以使用Arrays.copyOfRange
:
String[] newArray = Arrays.copyOfRange(colors, 1, colors.length);
忘了数组。 它们不是初学者的概念。 您可以更好地投入时间学习Collections API。
/* Populate your collection. */
Set<String> colors = new LinkedHashSet<>();
colors.add("Red");
colors.add("Orange");
colors.add("Yellow");
...
/* Later, create a copy and modify it. */
Set<String> noRed = new TreeSet<>(colors);
noRed.remove("Red");
/* Alternatively, remove the first element that was inserted. */
List<String> shorter = new ArrayList<>(colors);
shorter.remove(0);
为了与基于阵列的遗留API进行互操作, Collections
有一个方便的方法:
List<String> colors = new ArrayList<>();
String[] tmp = colorList.split(", ");
Collections.addAll(colors, tmp);
String[] colors = {"Red", "Orange", "Yellow"};
String[] copy = new String[colors.length - 1];
System.arraycopy(colors, 1, copy, 0, colors.length - 1);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.