Peter Zēng
Peter Zēng

Reputation: 37

Detecting Whole Words for JAVA

Currently with my program, if the user inputs "cat" then the chatbot would spit back out "Tell me more about your pets." as expected. However this is also true if the letters cat are part of another word. So a word like catch would be picked up as catch and the chatbot would return "Tell me more about your pets." How else would I go about to polish up the keyword detection?

if (statement.indexOf("cat") >=0) { response = "Tell me more about your pets.";

Upvotes: 0

Views: 338

Answers (2)

PeterK
PeterK

Reputation: 1723

You can use regex:

Pattern pattern = Pattern.compile("\\bcat\\b");
Matcher matcher = pattern.matcher("Hello the cat is cool");
boolean cat;
if(matcher.find()) {
  cat = true;
} else {
  cat = false;
}

Using \\b in the pattern, ensures that only full words are matched.

Upvotes: 2

kmac
kmac

Reputation: 115

A couple of ways to improve keyword detection:

  • Create a list/set of the keywords to compare to
  • Use the split(" ") function on your string to only get words (it returns a String[] that you can loop through)

Upvotes: 3

Related Questions