将数组中的字符串转换为二维数组中的单词

时间:2019-03-27 02:05:43

标签: java

我有一个程序在屏幕上显示歌词。每行歌词都存储在一个数组中。现在,我要创建一个二维数组,其中只包含以如下形式组织的单个单词:

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

我认为这只是一个简单的double for循环,它只需要当前字符串,去掉空格,并将单词存储在数组中。但是,当我尝试这种方法时,会出现类型不匹配的情况。

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+");
            }
        }

3 个答案:

答案 0 :(得分:1)

不需要内部for循环。

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));

   }
}

输出:

enter image description here

答案 1 :(得分:0)

您可以使用List,它非常动态并且易于控制。

    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());

答案 2 :(得分:0)

这是使用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));
    }
}

输出:

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