繁体   English   中英

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

[英]Converting strings in an array to words in a 2d array

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

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

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

   }
}

输出:

在此处输入图片说明

这是使用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]]

您可以使用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());

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM