newcoder1010 Posted August 19, 2022 Share Posted August 19, 2022 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 More sharing options...
Ingolme Posted August 20, 2022 Share Posted August 20, 2022 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 More sharing options...
newcoder1010 Posted August 20, 2022 Author Share Posted August 20, 2022 Thank you! Worked just fine. Link to comment Share on other sites More sharing options...
Recommended Posts
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 accountSign in
Already have an account? Sign in here.
Sign In Now