Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 602
user2966197 Avatar asked Apr 30 '14 04:04

user2966197


People also ask

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

You can use contains(), indexOf() and lastIndexOf() method to check if one String contains another String in Java or not. If a String contains another String then it's known as a substring. The indexOf() method accepts a String and returns the starting position of the string if it exists, otherwise, it will return -1.

How do I count repeated words in a string in Java?

First, we split the string by spaces in a. Then, take a variable count = 0 and in every true condition we increment the count by 1. Now run a loop at 0 to length of string and check if our string is equal to the word.


Video Answer


2 Answers

try regex

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

\b means word boundary

like image 72
Evgeniy Dorofeev Avatar answered Oct 20 '22 08:10

Evgeniy Dorofeev


Since you want to search a word there are three cases:

  1. word at start of sentence means no space at start but space at end.
  2. word between the sentence space at both ends.
  3. word at end only space at end.

To cover all the three cases, one possible solution is:

String str = "I am a JAVA programmer";
String[] splited = str.split("\\b+"); //split on word boundries
Arrays.asList(splited).contains("ram"); //search array for word

Here is working Demo

like image 21
Zaheer Ahmed Avatar answered Oct 20 '22 08:10

Zaheer Ahmed