【发布时间】:2014-04-06 16:59:58
【问题描述】:
我正在完成 Codingbat.com 上的一组在线练习,以供我自己消遣。一组练习侧重于递归编程。在其中一个练习中,我编写了以下函数来返回传递的字符串中 char 'x' 的频率:
public int countX(String str) {
/*Given a string, compute recursively (no loops) the number of lowercase 'x'
chars in the string.*/
if (str.length()< 1){
return 0;
}else if (str.charAt(0) == 'x'){
return countX(str.substring(1)) + 1;
}else{
return countX(str.substring(1));
}
}
根据 Codingbat 网站,这很好用。
下一个练习是计算字符串中子字符串“hi”的频率。我尝试调整我以前的方法,使用substring() 而不是charAt():
public int countHi(String str) {
/*Given a string, compute recursively (no loops) the number of times lowercase
"hi" appears in the string.*/
if (str.length()< 2){
return 0;
}else if (str.substring(0, 1).equals("hi")){
return countHi(str.substring(1)) + 1;
}else{
return countHi(str.substring(1));
}
}
但是,这总是返回 0。它看起来像测试条件
}else if (str.substring(0, 1).equals("hi")){
从未见过,但我不知道为什么。希望有人能帮忙!
编辑:
正如 Steve 和 JustinKSU 所指出的,我返回的是单个字符的子字符串。我认为substring() 方法中的索引号指的是字符的索引,就好像它们存储在一个数组中(其中 0 是第一个字符,1 秒等)。看起来更好的思考方式是substring() 索引表示字符串中字符分隔符的计数,从第一个字符之前的分隔符开始(这样substring(0, 1) 封装第一个字符)。
【问题讨论】:
-
substring()的第二个参数是exclusive。 docs.oracle.com/javase/7/docs/api/java/lang/…