5

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.in);

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

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



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

        System.out.println("This was programmed by -----");
srmjr
  • 97
  • 1
  • 1
  • 9

7 Answers7

15

You can keep track of the index:

int index = theString.indexOf("the");
while(index >= 0) {
    index = theString.indexOf("the", index+1);
    counter2++;
}
Carlos Afonso
  • 1,927
  • 1
  • 12
  • 22
  • No need for two `indexOf()` calls: `for (int idx = 0; (idx = theString.indexOf("the", idx)) >= 0; idx++) { counter2++; }` – Andreas Jul 27 '16 at 18:41
5

You have taken a complicated approach. Try this:

int count = str.split("the", -1).length - 1;

If you absolutely must use indexOf():

str = str.toLowerCase();
int count = 0;
for (int i = str.indexOf("the"); i >= 0; i = str.indexOf("the", i + 1))
    count++;
Bohemian
  • 412,405
  • 93
  • 575
  • 722
  • 1
    Thank you for your input, but I would like to specifically use indexOf – srmjr Jul 27 '16 at 18:09
  • Thank you. Is the .toLowerCase(); used to search for all instances of the word, regardless of case? – srmjr Jul 27 '16 at 18:37
  • @srmjr yes, your example indicated that the search should be case-insensitive. Doing the lowercase operation first makes the code easier to read and faster – Bohemian Jul 27 '16 at 19:03
  • Be aware that using `str.split` will not give the correct count if the target string is at the end of the string. This shouldn't be used if you can't guarantee the target string won't appear at the end of string. In the case, `str = "kkkthekkkthe"; int count = str.split("the").length - 1;`, count returns 1 but not 2. – Lynch Chen Dec 14 '20 at 19:49
  • 1
    @LynchChen good point. Fixed answer, which now calls version of split that retains trailing blank elements of result. See [live demo](https://ideone.com/SfJzck) that returns 2 for your example. – Bohemian Dec 14 '20 at 20:30
1

indexOf can take a second argument that says where to start in the string. So after you find the first occurrence, you can tell indexOf to only search the string after that index, etc.

This code should work:

public static void main(String[] args) {
    String theString = "The other day I went over there.";
    theString = theString.toLowerCase();

    int index = -1;
    int count = 0;

    while (true) {
        index = theString.indexOf("the", index + 1);
        if (index == -1) {
            break;
        } else {
            count += 1;
        }
    }

    System.out.printf("The string 'the' was found %d times.\n", count);

    // Output:
    // The string 'the' was found 3 times.
}
user94559
  • 59,196
  • 6
  • 103
  • 103
1

The indexOf(String str) method finds the index of the first occurrence of a str. So if you want to find all the occurrances of str then I'd suggest just implementing a loop in which you cut the string once you find an instance of str and look for str within theString again until it is no longer in theString. Here is what it should look like,

int index = theString.indexOf("the")
int count = 0;
while(index >= 0 && theString.length() > 0){
     count++;
     theString = theString.substring(0, index + "the".length());
     index = theString.indexOf("the");
}
Chris Gong
  • 8,031
  • 4
  • 30
  • 51
1

If you want to specifically use indexOf (I presume this is for an assignment), you can use a recursive method.

public static String numMatches (String str, String query) {
    int index = str.indexOf(query);
    if (index == -1) 
        return 0;
    else
        return 1 + numMatches(str.substring(index + query.length), query);
}
Jonathan Jeffrey
  • 432
  • 1
  • 3
  • 12
0

Maybe you can do something like this, you can use indexOf(String str)

String word = "We are students of the Department of Informatics. All students should know how to program in Java and C.";

    int findit = word.indexOf("students");
    int count = 0;

    for(int i=0; i<=findit; i++)
    {

        findit = word.indexOf("students" , findit + 1);

        count = count + 1;

    }

    System.out.print(count);
Mathias Stavrou
  • 871
  • 1
  • 8
  • 16
0

This checks how many occurrences of a string is inside a string.

             String str = oIn.nextLine();
             String st = oIn.nextLine();
             int countS = 0;
             int index3 = str3.indexOf(st);
             while (index >= 0){
             index = str.indexOf(st, index+1);
             countS++;          
             }
             System.out.println("The number of occurrences of "+st +" in the string " +str3 +" are "+countS);
JavaFTW
  • 3
  • 3
  • 6