java判断是否存在某个单词,如何使用Java检查句子中是否存在单词?

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:

Suppose my sentence is I am a, Java Programmer.

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;

}

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.

解决方案

try regex

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

\b means word boundary

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值