如何使用Java检查句子中是否存在单词? [英] How to check if a word is present in a sentence using Java?

查看:301
本文介绍了如何使用Java检查句子中是否存在单词?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是编程和处理函数的新手,如果句子中有单词,则返回true。我尝试了 indexOf()方法,但后来我也遇到了这种方法的某个问题:

I am new to programming and working on a function to return true if a word is present in a sentence. I tried the indexOf() method, but then I also came across a certain issue with this approach:

假设我的句子是我是Java程序员。

如果我们查找单词 ram 使用 indexOf()方法然后它将返回 true 因为 ram 出现在 Programmer 中,而正确的输出应为 false as ram 不是单词而是作为模式出现。

If we look for the word ram with the indexOf() method then it will return true because ram is present in Programmer while the correct output should be false as ram is not present as a word but as a pattern.

如何解决这个问题?我现在使用的代码是:

How can I work around this problem? The code that I am using as of now is:

boolean isPresent(String word, String sentence)
{
    if(sentence.indexOf(word) >= 0)
        return true;
    else
        return false;
}

注意:单词 ram 只是一个例子来说明我当前的方法存在的问题之一。我不是一直只能一直使用 ram 。这个词可以是任何说法 a ,后面跟着一个逗号。

NOTE: The word ram is just an example to show one of the issue with my current approach.It's not that I have to work with ram only all the time.The word can be any like say a which is followed by a comma in above sentence.

更新:感谢大家提供他们的意见和解决方案。我选择了一个作为接受的答案(如果允许,会选择更多:-)),但很多都很有用。

UPDATE: Thanks everyone for providing their comments and solutions. I have selected one as an accepted answer(would have selected more if permitted :-)), but a lot were helpful.

推荐答案

尝试正则表达式

boolean contains = s.matches(".*\\bram\\b.*");

\ b表示字边界

这篇关于如何使用Java检查句子中是否存在单词?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆