java - 将单词放入字符串数组中

标签 java arrays string

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/

相关文章:

java - Gradle 子项目设置、git 子模块

java - 使用 JUnit @Test(expected=Exception.Class) 捕获异常

php json多维数组语法

php - 如何将数组的值分布在三列中?

c - 如何在特定字符串后打印值

c++ - 在 Arduino 中使用字符串和整数访问/寻址变量

java - 如何使用 Spark 和 Java 来使用来自 Azure eventhub 的数据

java - ViewPager.SimpleOnPageChangeListener 不起作用

arrays - 向量化 Matlab 从头到尾替换数组值

r - 在 R 中查找字符串中的单词