Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

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