[英]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?
无论如何,我可以在循环内使用substring方法来做到这一点吗?
@Test
public void testCountOccurrences()
{
assertEquals(1, sc1.countOccurrences("ence"));
assertEquals(2, sc1.countOccurrences("en"));
assertEquals(1, sc2.countOccurrences("that"));
assertEquals(0, sc2.countOccurrences("This"));
}
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
. 该条件不取决于
i
或e
,而仅取决于sentence
和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. 所以只要
sentence
是长度至少为1的,你要么返回1或0。您的代码不能返回超过 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)
. 目前,这就是您的代码的问题-至于如何解决它,我将开始研究
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: 需要注意以下两种情况:
I'd also urge a couple of other changes: 我还敦促进行其他一些更改:
Object
- why? Object
的返回类型-为什么? Surely it's always going to return an integer, so a return type of int
would be more appropriate int
的返回类型会更合适 public Object countOccurrences(String string) {
int e = 0;
int i = 0;
while (i <= (sentence.length() - string.length() + 1)) {
if (sentence.substr(i, string.length() - 1).equals(string)) {
e++;
}
i++;
}
return e;
}
I didn't got to try it myself but it should work. 我没有必要亲自尝试,但是应该可以。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.