Jump to content

How to count duplicate words in a string


newcoder1010

Recommended Posts

Hello,         
 

        String words = "I go to summer school. I also go to winter school";
        int counter = 0;
        if(words.contains("go to")) {
            counter++;
        }
        System.out.println("counter " + counter);

As you can see "go to" is repeated twice. I like the counter to return the value of 2. But it returns 1. How can I count the duplicate words?

Link to comment
Share on other sites

You need a loop. You can use indexOf() and go changing the initial offset until you've found all the matches. When it returns -1 there are no more matches.

String words = "I go to summer school. I also go to winter school";
int counter = 0;
int start = words.indexOf("e");
while(start > -1) {
  counter++;
  start = words.indexOf("e", start + 1);
}
System.out.println("counter " + counter);

 

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...