Java Data Type How to - Check if a message contains a string








Question

We would like to know how to check if a message contains a string.

Answer

import java.util.regex.Matcher;
import java.util.regex.Pattern;
/*from  ww  w  .  j av a2 s.co  m*/
public class Main {

  public static void main(String argv[]) throws Exception {
    String once = "this is one SPAM";
    String twice = "this is : SPAM and SPAM";
    String thrice = "this is : SPAM and SPAM and ... again SPAM";

    System.out.println(countWordOccurrences(once, "SPAM"));
    System.out.println(countWordOccurrences(twice, "SPAM"));
    System.out.println(countWordOccurrences(thrice, "SPAM"));
  }

  private static int countWordOccurrences(String text, String word) {
    Matcher matcher = Pattern.compile(word).matcher(text);
    int count = 0;
    while (matcher.find()) {
      count++;
    }
    return count;
  }
}