Sobes.tech
Junior — Middle

How can you determine how many times a specific word appears in a string consisting of words?

sobes.tech AI

Answer from AI

To determine how many times a specific word occurs in a string, you can split the string into words using the split method, and then iterate over the resulting array to count matches.

Example in Java:

public class WordCount {
    public static int countOccurrences(String text, String word) {
        String[] words = text.split("\\s+"); // split by spaces
        int count = 0;
        for (String w : words) {
            if (w.equals(word)) {
                count++;
            }
        }
        return count;
    }

    public static void main(String[] args) {
        String text = "apple orange apple banana apple";
        String word = "apple";
        System.out.println(countOccurrences(text, word)); // Outputs 3
    }
}

If case sensitivity is important, you can use equalsIgnoreCase or convert words to a common case.

How can you determine how many times a specific word… - sobes.tech