【发布时间】:2012-11-28 18:45:39
【问题描述】:
int count(string s){
if(s == "")
return 0;
if(s.length == 1)
return 1;
return 1 + count() //This is what I can't figure out. How to traverse the string.
//I just need a hint, not a full on answer.
}
我不知道如何遍历字符串。
【问题讨论】:
-
提示:字符串的大小是 1 + 删除第一个(或最后一个)字符后的字符串大小。空字符串的大小为零。
-
对我来说听起来像是作业......现在你可能想要在倒数第二行做:return 1 + count(s.substr(0, s.length() - 1));
-
是的,这是家庭作业。没什么特别的,但它让我很烦。
-
您确定您需要使用
std::string与char*吗?if(s.length == 1)看起来几乎像作弊:) -
您使用字符串的
length方法,该方法已经返回大小。这个练习有什么意义?
标签: c++ string recursion counting