0

How do I create a new array from this array

String[] data = {"day: monday, color: green", "day: sunday, color: blue", "day: thursday, color: red"};

that looks like this:

String[] data = {"green", "blue", "red"};

2 Answers 2

3

First, create new array of the same size:

String[] colors = new String[data.length];

Then iterate over the source array parse each value and put it to the result. There are a lot of ways to parse your strings. It depends on how strong the parsing should be. Here is the simplest way:

for (int i = 0; i < data.length; i++) {
    String[] d = data[i].split(" ");
    colors[i] = d[d.length - 1];
}

No more comments. Try to understand the code yourself. It is really trivial.

Sign up to request clarification or add additional context in comments.

Comments

0

I agree with what AlexR says about figuring it out for yourself. Here's another way to envision the for-loop and parse operation using the substring() method. Again, be sure to preallocate a String array to hold the results before hand, ie:

String[] result = new String[data.length];

for(int i = 0; i < data.length; i++){

    // gets the substring starting on the 5th character
    String color = data[i].substring(5);

    // adds String to result
    result[i] = color;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.