play minecraft
play minecraft

Reputation: 23

Converting strings in an array to words in a 2d array

I have a program that displays lyrics on screen. Each line of lyrics is stored in an array. Now from this, I want to create a 2d array with just the individuals words organized in lines like this:

String[] lyrics = {"Line number one", "Line number two"};
String[][] words = {{"Line","number","one"},{"Line", "number", "two"}};

I thought it would just be a simple double for loop that just takes current string, gets rid of spaces, and stores words in array. When I try this however, I get a type mismatch.

public static void createWordArray() {
        for(int i=0; i<=lyrics.length; i++) {
            for(int j =0; j<=lyrics[i].length(); i++) {
                words[i][j] = lyrics[i].split("\\s+");
            }
        }

Upvotes: 1

Views: 146

Answers (3)

Ram K
Ram K

Reputation: 1785

Here is an example solution using Streams.

public class WordArrayUsingStreams {
    public static void main(String[] args) {
        String[] lyrics = {"Line number one", "Line number two"};

        String[][] words = Arrays.stream(lyrics)
              .map(x -> x.split("\\s+"))
              .toArray(String[][]::new);

        System.out.println(Arrays.deepToString(words));
    }
}

Output :

[[Line, number, one], [Line, number, two]]

Upvotes: 1

YouDontKnowAboutBear
YouDontKnowAboutBear

Reputation: 28

You can use List , which is much dynamic and easy to control.

    String[] lyrics = {"Line number one", "Line number two"};

    //Create a List that will hold the final result
    List<List<String>> wordsList = new ArrayList<List<String>>();

    //Convert the array of String into List
    List<String> lyricsList = Arrays.asList(lyrics);

    //Loop over the converted array
    for(String s : lyricsList )
    {
        //Split your string
        //convert it to a list
        //add the list into the final result
        wordsList.add(Arrays.asList(s.split("\\s+")));
    }

        //System.out.println(wordsList.toString());

Upvotes: 0

javapedia.net
javapedia.net

Reputation: 2731

The inner for loop is not required.

public class CreateWordArray {
    static String[]  lyrics = {"Line number one", "Line number two"}; 
    static String[][] words = new String[lyrics.length][];

    public static void createWordArray() {
        for(int i=0; i<lyrics.length; i++) {
                words[i] = lyrics[i].split("\\s+");
        }
    }

   public static void main(String[] s) {

       createWordArray();
       System.out.println(Arrays.deepToString(words));

   }
}

Output:

enter image description here

Upvotes: 1

Related Questions