1

How can i convert a String[] array into a String[][]? For example, if the String[] was like this: String[] array = new String[]{"Artist,Song,Genre"}; How can i convert that into a String[][] so that "Artist" is in one "cell" e.g String[0][0] = "Artist";

Thank you.

0

2 Answers 2

3

Try this:

String[] array = new String[]{"a,b,c", "1,2,3", "x,y,z"};

String[][] twoDim = new String[array.length][];

for (int i = 0; i < twoDim.length; i++)
    twoDim[i] = array[i].split(",");

System.out.println(Arrays.deepToString(twoDim));

Prints:

[[a, b, c], [1, 2, 3], [x, y, z]]

Or perhaps this is what you're after:

String[][] twoDim = { { "Artist1", "Song1", "Genre1" },
                      { "Artist2", "Song2", "Genre2" },
                      { "Artist3", "Song3", "Genre3" } };
Sign up to request clarification or add additional context in comments.

1 Comment

what if the array was populated to more than one index, i would have to implement a for loop how?
0

Do you mean something like:

String[][] array = new String[][] {
    new String[] {
        "Artist", "Genre", "Song"
    },
    new String[] {
        "artist1", "genre1", "song1"
    },
    new String[] {
        "artist2", "genre2", "song2"
    }
};

1 Comment

You don't need the new Strings... see my answer.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.