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.
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.
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.
try regex
boolean contains = s.matches(".*\\bram\\b.*");
\b means word boundary
Since you want to search a word there are three cases:
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With