[英]Java string[] partial copying
How do I take a String[]
, and make a copy of that String[]
, but without the first String? 如何获取
String[]
,并复制该String[]
,但没有第一个String? Example: If i have this... 示例:如果我有这个......
String[] colors = {"Red", "Orange", "Yellow"};
How would I make a new string that's like the string collection colors, but without red in it? 我如何制作一个新的字符串,就像字符串集合颜色,但没有红色?
你可以使用Arrays.copyOfRange
:
String[] newArray = Arrays.copyOfRange(colors, 1, colors.length);
Forget about arrays. 忘了数组。 They aren't a concept for beginners.
它们不是初学者的概念。 Your time is better invested learning the Collections API instead.
您可以更好地投入时间学习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);
For inter-operating with array-based legacy APIs, there is a handy method in Collections
: 为了与基于阵列的遗留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.