indexOf to find all occurrences of a word in a String
Asked Answered
E

7

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 -----");
Exemplum answered 27/7, 2016 at 18:5 Comment(3)
I would recommend searching with a regular expression instead.Schouten
Would you mind explaining what you mean by regular expression?Exemplum
Duplicate question, the question was previously answered in this postNaif
C
15

You can keep track of the index:

int index = theString.indexOf("the");
while(index >= 0) {
    index = theString.indexOf("the", index+1);
    counter2++;
}
Caelian answered 27/7, 2016 at 18:16 Comment(1)
No need for two indexOf() calls: for (int idx = 0; (idx = theString.indexOf("the", idx)) >= 0; idx++) { counter2++; }Guelph
G
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++;
Grouping answered 27/7, 2016 at 18:8 Comment(5)
Thank you for your input, but I would like to specifically use indexOfExemplum
Thank you. Is the .toLowerCase(); used to search for all instances of the word, regardless of case?Exemplum
@Exemplum yes, your example indicated that the search should be case-insensitive. Doing the lowercase operation first makes the code easier to read and fasterGrouping
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.Kathernkatheryn
@LynchChen good point. Fixed answer, which now calls version of split that retains trailing blank elements of result. See live demo that returns 2 for your example.Grouping
T
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.
}
Trawl answered 27/7, 2016 at 18:14 Comment(0)
M
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");
}
Marquardt answered 27/7, 2016 at 18:22 Comment(2)
This is wrong. The while loop will be stuck in an infinite loop as the variable index is never updated.Schouten
@JonathanJeffrey Thank you, I just fixed it. This was a lazy error on my part.Marquardt
S
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);
}
Schouten answered 27/7, 2016 at 18:22 Comment(0)
J
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);
Jacaranda answered 6/6, 2017 at 22:36 Comment(0)
C
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);
Conjunctiva answered 9/1, 2018 at 0:11 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.