首页javastringJava Data Type - 如何检查消息是否包含字符串

Java Data Type - 如何检查消息是否包含字符串

我们想知道如何检查消息是否包含字符串。
import java.util.regex.Matcher;
import java.util.regex.Pattern;

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;
  }
}