How to check if a word is present in a sentence using Java?

user2966197 picture user2966197 · Apr 30, 2014 · Viewed 78.7k times · Source

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.

Answer

Evgeniy Dorofeev picture Evgeniy Dorofeev · Apr 30, 2014

try regex

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

\b means word boundary