How do i find how many times a substring is used in a string?

public Object countOccurrences(String string)
{
    int e = 0;
    int i = 0;
    while ( i < sentence.length())
    {
        if(sentence.contains(string))
        {
            e++;
            i++;
            return e;
        }
        else
        {
            break;
        }
    }
    return e;
}

What is wrong with my code that won't allow me to pass the test? is there anyway I can use the substring method inside a loop to do this?

@Test
public void testCountOccurrences()
{
    assertEquals(1, sc1.countOccurrences("ence"));
    assertEquals(2, sc1.countOccurrences("en"));
    assertEquals(1, sc2.countOccurrences("that"));
    assertEquals(0, sc2.countOccurrences("This"));

}
Jon Skeet
people
quotationmark

What is wrong with my code that won't allow me to pass the test?

Before doing anything else, you should consider how you could have worked out what was wrong for your code to start with. Did you debug through it? At what point did it behave differently to how you expected it to? If you haven't learned how to use a debugger yet, now is a great time to start.

As for the next step, look at this code:

if(sentence.contains(string))
{
    e++;
    i++;
    return e;
}

That condition doesn't depend on i or e, just on sentence and string. So as long as sentence is of length at least 1, you'll either return 1 or 0. Your code can never return more than 1.

That's what's wrong with your code at the moment - as for how to fix it, I'd start looking at String.indexOf(String, int). In other words, you want to find the first occurrence, then find the next occurrence, then the next occurrence, until you can't find any more. (Use the return value to work out where to start looking on the next iteration, as well as checking that there was a match.)

A couple of situations to be careful of:

  • How many times does "abbbc" contain "bb"?
  • How many times does "abbbc" contain ""?

I'd also urge a couple of other changes:

  • Your method has a return type of Object - why? Surely it's always going to return an integer, so a return type of int would be more appropriate
  • This is a great candidate for parameterized testing. Look into how you can effectively separate your single test into multiple test cases which can pass or fail independently, but without the source overhead of lots of test methods... (Hint: each test case should have the sentence, the text you're looking for, and the expected number of matches.)

people

See more on this question at Stackoverflow