How do I take a String[]
, and make a copy of that String[]
, but without the first 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?
Using the copyOfRange() method you can copy an array within a range. This method accepts three parameters, an array that you want to copy, start and end indexes of the range. You split an array using this method by copying the array ranging from 0 to length/2 to one array and length/2 to length to other.
The easiest option would be to iterate through your string array and do a . contains on each individual String. for(int i = 0; i < s. length; i++){ if(s[i].
To make a copy of a string, we can use the built-in new String() constructor in Java. Similarly, we can also copy it by assigning a string to the new variable, because strings are immutable objects in Java.
As we know that String is an immutable object, so we can just assign one string to another for copying it. If the original string value will change, it will not change the value of new String because of immutability.
You could use 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.
/* 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
:
List<String> colors = new ArrayList<>();
String[] tmp = colorList.split(", ");
Collections.addAll(colors, tmp);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With