3 回答
TA贡献1911条经验 获得超7个赞
内部 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));
}
}
输出:
TA贡献2080条经验 获得超4个赞
下面是使用流的示例解决方案。
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]]
TA贡献1993条经验 获得超5个赞
您可以使用 列表 ,这是非常动态且易于控制的。
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());
添加回答
举报