Reputation:
im struggling to figure out where the error in my code is;
here is my test:
@Test
public void testCountOccurences()
{
assertEquals(1, sc1.countOccurences("ence"));
assertEquals(2, sc1.countOccurences("en"));
assertEquals(1, sc2.countOccurences("that"));
assertEquals(0, sc2.countOccurences("This"));
}
here is my method:
public int countOccurences(String t)
{
int j = 0;
int i;
for(i = 0; i < sentence.length(); i++)
{
String subString = sentence.substring(i, i + t.length());
if(subString.equals(t))
{
j++;
}
}
return j;
}
Upvotes: 2
Views: 152
Reputation: 121712
You can use String.indexOf()
for that:
public int countOccurrences(final String t)
{
if (t == null || t.isEmpty())
return 0;
int index, startIndex = 0;
int len = t.length();
int ret = 0;
while (true) {
index = sentence.indexOf(t, startIndex);
if (index == -1)
break;
startIndex = index + len;
ret++;
}
return ret;
}
Upvotes: 1
Reputation: 4341
I'm betting your problem is i + t.length(). When 'i' is close to the length of your sentence, then i+t.length will be longer than the sentence, and you'll get an error.
Upvotes: 0
Reputation: 75545
I am going to assume that you're doing this as an exercise.
It seems that you are going off the end of the original string.
Try changing for(i = 0; i < sentence.length(); i++)
to for(i = 0; i < sentence.length() - t.length(); i++)
.
Upvotes: 3