两个字符串的递归比较
Recursive comparison of two strings
函数int compare(...)检查2个字符串是否相等,忽略大小写和任何非字母字符,例如"a?...!b"等同于"ab"。如果相等,则返回 1,否则返回 0。但是,我的代码中有一个错误!
int compare(const char* string1, const char* string2)
{
if(string1 == NULL || string2 == NULL)
return 0;
std::cout << *string1 << " | " << *string2 << std::endl;
if((!isalpha(*string1) && *string1 != ' ') && (!isalpha(*string2) && *string2 != ' '))
{
compare(++string1,++string2);
}
else if(!isalpha(*string1) && *string1 != ' ')
{
compare(++string1,string2);
}
else if(!isalpha(*string2) && *string2 != ' ')
{
compare(string1, ++string2);
}
if(tolower(*string1) != tolower(*string2))
return 0;
if(*string1 == ' ')
return 1;
if(*string1 == *string2)
compare(++string1, ++string2);
}
例如,如果我尝试运行此代码:
compare("a !!!b", "a b");
输出真的让我感到困惑:
a | b
|
! |
! |
! |
b | b
^@| ^@
| a
^@| ^@
| a
它返回 0(不等于)。一旦到达 b | b,它就不会停止运行,为什么?
除了需要return
语句之外,你的逻辑还有一个缺陷。您需要检查两个字符串是否为空,因此在函数的前面是否相等:
int compare(const char* string1, const char* string2)
{
if(string1 == NULL || string2 == NULL)
return 0;
// This needs to go here
if(*string1 == ' ' && *string2 == ' ') {
return 1;
}
std::cout << *string1 << " | " << *string2 << std::endl;
if((!isalpha(*string1) && *string1 != ' ') && (!isalpha(*string2) && *string2 != ' '))
{
return compare(++string1,++string2);
}
else if(!isalpha(*string1) && *string1 != ' ')
{
return compare(++string1,string2);
}
else if(!isalpha(*string2) && *string2 != ' ')
{
return compare(string1, ++string2);
}
if(tolower(*string1) != tolower(*string2))
return 0;
if(*string1 == *string2)
return compare(++string1, ++string2);
}
你可以在这里查看:https://ideone.com/Si78Nz
相关文章:
- 通过递归进行因子分解
- 递归函数计算序列中的平方和(并输出过程)
- 使用递归的数组的最小值.这是怎么回事
- 递归列出所有目录中的C++与Python与Ruby的性能
- 递归计数给定目录的文件和所有目录
- 如何在BST的这个简单递归实现中消除警告
- C++:正在检查LinkedList中的回文-递归方法-错误
- 递归模板化函数不能分配给具有常量限定类型"const tt &"的变量"state"
- 递归无序映射
- TSP递归解的迭代形式
- 如何在Elixir中调用递归函数并行
- 返回递归调用和仅递归调用的区别
- 数组元素打印的递归方法
- 使用递归时获取变量的奇怪值
- 如何在C++中递归地按相反顺序打印集合
- 重载 == 以递归方式比较两个链表
- 两个字符串的递归比较
- 如何创建一个递归方法来比较两个值
- 如何递归比较向量
- 在我的简单测试中,Java在递归算法速度比较上胜过c++