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;
}
我的代碼有什麼問題不會讓我通過測試?無論如何,我可以使用循環內的子串方法來做到這一點?如何查找在字符串中使用子串的次數?
@Test
public void testCountOccurrences()
{
assertEquals(1, sc1.countOccurrences("ence"));
assertEquals(2, sc1.countOccurrences("en"));
assertEquals(1, sc2.countOccurrences("that"));
assertEquals(0, sc2.countOccurrences("This"));
}
我建議使用模式/匹配器: 請參閱示例: http://stackoverflow.com/questions/7378451/java-regex-match-count –