簡體   English   中英

Java string []部分復制

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM