Skip to content

indexOf to find all occurrences of a word in a String

I’m trying to use indexOf to find all occurrences of the characters ‘the’ in a sentence. For example, if the sentence were “The other day I went over there”, it should return 3.

I am able to do this up to the point where it finds the first index, but I’m unsure of how to write the loop. I originally had a for loop that searched the entire string, but it was returning the full string character length, instead of the occurrences of my specified character. How can I write a loop that will find all of the occurrences of the word? Thank you.

import java.util.Scanner;

public class TheFinder
    public static void main (String[] args)
        String theString = "";
        Scanner enter = new Scanner(;

        System.out.println("Please enter a sentence: ");
        theString = enter.nextLine();
        int counter2 = 0;

        if (theString.indexOf("the")!= -1)

        System.out.printf("The characters 'the' were found %d times", counter2);

        System.out.println("This was programmed by -----");


You can keep track of the index:

int index = theString.indexOf("the");
while(index >= 0) {
    index = theString.indexOf("the", index+1);