public static String[] wordList(String line){
Scanner scanner = new Scanner(line);
String[] words = line.split(" ");
for( int i=0; i<words.length; i++)
{
String word = scanner.next();
return words[i] = word;
}
scanner.close();
}
在 return Words[i] = word;
行上,我收到错误消息“无法将 String 转换为 String[]”。帮忙?
最佳答案
line.split()
已经给你一个数组,你只需要返回它:
public class Test {
public static String[] wordList(String line){
return line.split(" ");
}
public static void main(String args[]) {
String xyzzy = "paxdiablo has left the building";
String[] arr = wordList(xyzzy);
for (String s: arr)
System.out.println(s);
}
}
运行给出:
paxdiablo
has
left
the
building
请记住,每个单词之间有一个空格。如果您想要一个使用“任意数量的空白”分隔符的更通用的解决方案,您可以使用它:
public static String[] wordList(String line){
return line.split("\\s+");
}
可以与String.split()
一起使用的正则表达式可以在 here 中找到。 .
关于java - 将单词放入字符串数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28666356/