繁体   English   中英

拆分一个句子忽略Java中的字符

[英]Split a sentence ignoring characters in Java

我想编写一个程序来读取一行输入文本并将其分解为单词。

(解决方案)单词应每行输出一个。 一个词被定义为一个字母序列。

输入中任何不是字母的字符都应该被丢弃。

例如,如果用户输入以下行:

He said, "That’s not a good idea."

那么程序的输出应该是:

He
said
That
‘s
not
a
good
idea

只需使用正则表达式

    Pattern pattern = Pattern.compile("[\\w'’]+");
    Matcher matcher = pattern.matcher("He said, \"That’s not a good idea.\"");
    while (matcher.find())
        System.out.println(matcher.group());

尝试这个:

public class Main {
    public static void main(String[] args) {
        Scanner stdIn = new Scanner(System.in); // user input
        String line = stdIn.nextLine(); // read line
        String[] words = line.split("[^a-zA-Z]+"); // split by all non-alphabetic characters (a regex)
        for (String word : words) { // iterate through the words
            System.out.println(word); // print word with a newline
        }
    }
}

这将不包括在令牌撇号's ,但我不知道为什么你认为包含。 毕竟,这不是一封信,我读了你的第一个粗体句子。 我希望评论有助于解释它是如何工作的。 将有一个尾随空行,但如果您确实需要,这应该很容易修复。

暂无
暂无

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

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