If you need to search for an occurrence of a word in a sentence, there are several methods in the
String class that can help. The simplest is probably
contains(). For example,
Quote:String quote = "You blocks, you stones, you worse than senseless things!";
boolean hasYou = quote.contains("you");
boolean hasBlock = quote.contains("block");
boolean hasJuliet = quote.contains("Juliet");
println("Contains 'you': "+hasYou);
println("Contains 'block': "+hasBlock);
println("Contains 'Juliet': "+hasJuliet);
A few things to watch out for though with this simple example:
1. This example is a case-sensitive match, so 'you' would not, for example, match with 'You'. If you want to do a case insensitive search, convert the sentence and the keywords into lowercase using the
toLowercase()2. This example would not count the number of matches if there is more than one occurrence in a single sentence. If you need to do that, you are probably best splitting the sentence into tokens.
3. This example would match matches within longer words (e.g. it would match 'you' with 'youth'. Again, the best way to avoid this would be to break the sentence down into individual words with
split() and then do an
equalsIgnoreCase() on each word.
I would recommend looking at the
String API documentation for a longer list of possibly useful methods.