Java-如何解析字符串中的特定单词
我将如何解析“嗨,你好吗?”这句话中的“嗨”一词? 或者在“你好吗?”中解析“怎么样”这个词?
我想要的代码示例:
String word = "hi";
String word2 = "how";
Scanner scan = new Scanner(System.in).useDelimiter("\n");
String s = scan.nextLine();
if(s.equals(word)) {
System.out.println("Hey");
}
if(s.equals(word2)) {
System.out.println("Hey");
}
How would I parse for the word "hi" in the sentence "hi, how are you?"
or in parse for the word "how" in "how are you?"?
example of what I want in code:
String word = "hi";
String word2 = "how";
Scanner scan = new Scanner(System.in).useDelimiter("\n");
String s = scan.nextLine();
if(s.equals(word)) {
System.out.println("Hey");
}
if(s.equals(word2)) {
System.out.println("Hey");
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
我会选择 tokenizer,相反。
将空格和其他元素(如逗号、句号等)设置为分隔符。并记住在不区分大小写的模式下进行比较。
这样,您就可以在“嗨,他的测试进行得怎么样”中找到“hi”,而不会在“his”上出现误报,在“Hi”上出现误报(以大写 H 开头)。
I'd go for a tokenizer, instead.
Set space and other elements like commas, full stops etc. as delimiters. And rememeber to compare in case-insensitive mode.
This way you can find "hi" in "Hi, how is his test going" without getting a false positive on "his" and a false negative on "Hi" (starts with a uppercase H).
您可以将正则表达式传递给
扫描仪
。因此,您可以迭代输入中的每个单词(扫描仪默认情况下以空格分隔),并在获得匹配项时执行适当的处理。You can pass a regular expression to the
next()
method ofScanner
. So you can iterate through each word in the input (Scanner delimits on whitespace by default) and perform the appropriate processing if you get a match.要查找子字符串,您可以使用
contains
或indexOf
或任何其他变体:http://java.sun.com/j2se/1.5.0/docs/api/java/lang/String.html
如果您关心字边界,那么
StringTokenizer
可能是一个好方法。https://docs.oracle.com/ javase/1.5.0/docs/api/java/util/StringTokenizer.html
然后,您可以对每个单词执行不区分大小写的检查 (equalsIgnoreCase)。
To just find the substring, you can use
contains
orindexOf
or any other variant:http://java.sun.com/j2se/1.5.0/docs/api/java/lang/String.html
If you care about word boundaries, then
StringTokenizer
is probably a good approach.https://docs.oracle.com/javase/1.5.0/docs/api/java/util/StringTokenizer.html
You can then perform a case-insensitive check (equalsIgnoreCase) on each word.
看起来像是正则表达式的工作。
Contains
会给出一个误报,比如“hire-purchase”
。Looks like a job for Regular Expressions.
Contains
would give a false positive on, say,"hire-purchase"
.我会选择
java.util.StringTokenizer
:https://docs.oracle.com/javase/1.5.0/docs/api/java/util/StringTokenizer.html或者,看看
java .util.regex
并使用正则表达式。I'd go for the
java.util.StringTokenizer
: https://docs.oracle.com/javase/1.5.0/docs/api/java/util/StringTokenizer.htmlAlternatively, take a look at
java.util.regex
and use regular expressions.