2012-06-03 30 views
6

如何取String[],並複製該String[],但沒有第一個字符串? 例如:如果我有這個...Java字符串[]部分複製

String[] colors = {"Red", "Orange", "Yellow"}; 

我怎麼會做出新的字符串,就像字符串集合的顏色,但不紅呢?

回答

14

你可以使用Arrays.copyOfRange

String[] newArray = Arrays.copyOfRange(colors, 1, colors.length); 
+0

感謝的人!我真的很喜歡它! – Barakados

5
String[] colors = {"Red", "Orange", "Yellow"}; 
String[] copy = new String[colors.length - 1]; 
System.arraycopy(colors, 1, copy, 0, colors.length - 1); 
8

忘記陣列。他們不是初學者的概念。您的時間更適合投入學習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); 
+1

+1有知識,就有智慧。 –

+1

不應該'short.remove(0)'去除第一個元素? – SHiRKiT

+0

@SHiRKiT哎呀,是的,謝謝! – erickson