1

HI, so my code compiles but does not give the result I intended. Any help is greatly appreciated!

public class SubstringCounter
{
    public static int substringCounter(String master,  String substring)
    { int count = 0 ;

        for(int pos = 0 ; pos < master.length() ; pos++)
        {
            int index = master.indexOf(substring, pos) ; 
            if(index!=0){
                pos = count ; 
                count++ ; 

            }
        }

        return count ;

    }
}

Edited by JamesCherrill: Moved to a new thread

3
Contributors
4
Replies
30
Views
2 Weeks
Discussion Span
Last Post by JamesCherrill
0

An explanation of what your code is supposed to do and what it is doing wrong is essential to getting someone to help you. Remember to include sample inputs, their results, and what you expect

1

Look again at line 10. Did you really intend to set pos back to 1 , 2, 3 etc? Or were you hoping to set it just after the last place where you found the substring?

Edited by JamesCherrill

0

Due: Wednesday, November 1, 2017 at 11:59 pm
How can we count the number of occurrences of a character or group of characters (a substring) inside of a given string of characters? In other words, how can we count the number of time a certain section of text appears in another section of text?

Your assignment is to write a SubstringCounter class with only one method:

public static int substringCounter(String string, String substring)

The method will utilize two strings as passed parameters. The first string is the master string to be searched, and the second string is the string being searched for. The method returns the count (an integer) of the number of times the substring is found in the master string. You should assume that either the master string or the substring is one or more characters, and that either one may be longer than the other. The substring (obviously) may occur one or more times in the master string, or possibly not at all. You will want to have some kind of process that will look at each of the characters in the master string and count every time the substring is found.

If you are not sure exactly how you want to do this, you will want to review the advanced operations on strings section of the textbook, and in particular the string method descriptions listed on pages 265-6. You will also want to look at the IndexOfExample and SubstringExample classes that are provided for you in the project download.

To get started, download, extract, and save the Substring Counter project to your computer. Open up the project by clicking on the BlueJ package file icon. You can run the SubstringCounterTest class anytime you like to see how much of the assignment you have completed (go ahead, and give it a try right now). When you have written your method, run the tester and see if your code passes the 10 rigorous tests.