我对递归很陌生。我需要写两个函数。到目前为止,我写了一个,它有权找到一个字符串的长度。然而,第二个,即:在数组中找到重复字符被证明是非常困难的。我已经在网上搜索过试图找到例子,我已经做了很多阅读,但到目前为止什么都没有。因此,如果您能指出正确的方向,我将不胜感激。
谢谢
//length( ) -- this function is sent a null terminated array of characters.
//The function returns the length of the "string".
long slength (const char ntca[])
{
int length = 0;
if (ntca[length] == '\0'){
return 0;
}
else{
return slength(ntca+1)+1;
}
}
//countall( ) -- This function is sent a null terminated array of characters
//and a single character. The function returns the number of times the character
//appears in the array.
long countall (const char ntca[],char letter){
int position = 0;
int counter = 0;
long length = slength(ntca);
if (length == 0)
return 0;
else if (ntca[position]==letter)
return 1 + countall(ntca-1,letter);
else
return countall(ntca,letter);
}
最佳答案
你可以试试下面的代码:
long countall(const char *ptr, char letter)
{
if(!*ptr) return 0; //base case
return (*ptr == letter) + countall(ptr + 1, letter);
}
递归的基本情况是函数遇到字符串的末尾。对于 空字符串
和任何字母,答案为 0
。
如果字符串不为空,当且仅当当前字符匹配字母
时,我们将 1
添加到 recursive call on shorter string
的结果中>.
关于c++ - 使用递归查找数组中字符出现的次数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19966432/