Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java string[] partial copying

Tags:

java

string

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?

like image 963
Barakados Avatar asked Jun 03 '12 05:06

Barakados


People also ask

How do you copy half an array?

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.

How do you match a partial string in Java?

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

How do you make a copy of a string in Java?

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.

Can we assign one string to another 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.


2 Answers

You could use Arrays.copyOfRange:

String[] newArray = Arrays.copyOfRange(colors, 1, colors.length);
like image 179
Paul Bellora Avatar answered Oct 11 '22 04:10

Paul Bellora


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);
like image 23
erickson Avatar answered Oct 11 '22 03:10

erickson