将数组中的字符串转换为 2d 数组中的单词

我有一个在屏幕上显示歌词的程序。每行歌词都存储在一个数组中。现在,从这个开始,我想创建一个2d数组,其中只有个人单词组织成这样的行:


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

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

我以为它只是一个简单的双精度循环,它只是获取当前字符串,去掉空格,并将单词存储在数组中。但是,当我尝试此操作时,我得到的类型不匹配。


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

            }

        }


DIEA
浏览 106回答 3
3回答

Smart猫小萌

内部 for 循环不是必需的。public class CreateWordArray {&nbsp; &nbsp; static String[]&nbsp; lyrics = {"Line number one", "Line number two"};&nbsp;&nbsp; &nbsp; static String[][] words = new String[lyrics.length][];&nbsp; &nbsp; public static void createWordArray() {&nbsp; &nbsp; &nbsp; &nbsp; for(int i=0; i<lyrics.length; i++) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; words[i] = lyrics[i].split("\\s+");&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; &nbsp;public static void main(String[] s) {&nbsp; &nbsp; &nbsp; &nbsp;createWordArray();&nbsp; &nbsp; &nbsp; &nbsp;System.out.println(Arrays.deepToString(words));&nbsp; &nbsp;}}输出:

犯罪嫌疑人X

下面是使用流的示例解决方案。public class WordArrayUsingStreams {&nbsp; &nbsp; public static void main(String[] args) {&nbsp; &nbsp; &nbsp; &nbsp; String[] lyrics = {"Line number one", "Line number two"};&nbsp; &nbsp; &nbsp; &nbsp; String[][] words = Arrays.stream(lyrics)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .map(x -> x.split("\\s+"))&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .toArray(String[][]::new);&nbsp; &nbsp; &nbsp; &nbsp; System.out.println(Arrays.deepToString(words));&nbsp; &nbsp; }}输出:[[Line, number, one], [Line, number, two]]

ibeautiful

您可以使用 列表 ,这是非常动态且易于控制的。&nbsp; &nbsp; String[] lyrics = {"Line number one", "Line number two"};&nbsp; &nbsp; //Create a List that will hold the final result&nbsp; &nbsp; List<List<String>> wordsList = new ArrayList<List<String>>();&nbsp; &nbsp; //Convert the array of String into List&nbsp; &nbsp; List<String> lyricsList = Arrays.asList(lyrics);&nbsp; &nbsp; //Loop over the converted array&nbsp; &nbsp; for(String s : lyricsList )&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; //Split your string&nbsp; &nbsp; &nbsp; &nbsp; //convert it to a list&nbsp; &nbsp; &nbsp; &nbsp; //add the list into the final result&nbsp; &nbsp; &nbsp; &nbsp; wordsList.add(Arrays.asList(s.split("\\s+")));&nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; //System.out.println(wordsList.toString());
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python