【问题标题】:Split a sentence ignoring characters in Java在Java中拆分一个忽略字符的句子
【发布时间】:2015-08-29 18:53:50
【问题描述】:
我想编写一个程序来读取一行输入文本并将其分解成单词。
(解决方案)
单词应该每行输出一个。一个词被定义为一个字母序列。
输入中的任何非字母字符都应丢弃。
例如,如果用户输入以下行:
He said, "That’s not a good idea."
那么程序的输出应该是:
He
said
That
‘s
not
a
good
idea
【问题讨论】:
-
纯代码编写请求在 Stack Overflow 上是题外话——我们希望这里的问题与特定编程问题有关——但我们很乐意帮助您自己编写!告诉我们what you've tried,以及您遇到的问题。这也将有助于我们更好地回答您的问题。
标签:
java
string
loops
split
【解决方案1】:
只需使用正则表达式
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());
【解决方案2】:
试试这个:
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 中包含撇号,但我不知道您为什么包含它。毕竟,这不是一封信,我读了你的第一个粗体字。我希望 cmets 帮助解释它是如何工作的。后面会有一个空行,但如果你真的需要,这应该很容易修复。