我需要编写一个使用递归来比较两个字符串的程序,比如S1和s2,分别返回s1 > S2、s1 == s2和s1 < s2的1、0和-1。
对于这个任务,我很遗憾不能使用任何string.h .h库。
我是递归的初学者,掌握了处理整数/数组场景的诀窍。但是,在处理这些问题时,我似乎不能确定“终止条件”和“递归条件”,我寻求大家对这件事的善意指导。
主体是由我的教授提供的模板,所以我真的不能做任何事情来编辑它的这一部分。
#include <stdio.h>
#include <string.h>
#define INIT_VALUE 100
int rStrcmp(char *s1, char *s2);
int main()
{
char source[40], target[40], *p;
int result = INIT_VALUE;
printf("Enter a source string: \n");
fgets(source, 40, stdin);
if (p=strchr(source,'\n')) *p = '\0';
printf("Enter a target string: \n");
fgets(target, 40, stdin);
if (p=strchr(target,'\n')) *p = '\0';
result = rStrcmp(source, target);
printf("rStrcmp(): %d", result);
return 0;
} 到目前为止,我编写的递归代码:
int rStrcmp(char *s1, char *s2)
{
// The terminating conditions:
if (*s1 == '\0' && *s2 == '\0') // both strings end together
return 0;
else if (*s1 == '\0') // s1 ends first (s1 smaller)
return ‐1;
else if (*s2 == '\0') // s2 ends first (s1 larger)
return 1;
else if (*s1 < *s2) // ASCII char in s1 < s2 : (s1 smaller)
return ‐1;
else if (*s1 > *s2) // ASCII char in s1 > s2 : (s1 larger)
return 1;
else // recursive condition
{
rStrcmp(s1+1,s2+1) // moves the address to point to the next char
}
}我想我大概知道我的错误是什么,就是我在比较地址中的整个字符串,而不是单个字符。无论如何,我是否可以编写程序,以便比较两个字符串中的每个字符?
在这件事上寻求大家的善意指导。我可以很容易地使用迭代来解决这个问题,但是我必须用递归来解决它,而且我不能真正理解字符串的递归。
编辑:这个程序可以编译和运行。但是,当我输入测试用例时,例如:
s1 = abc123 s2 = abc123f
输出返回一个1,实际上应该是-1。
或
s1 = abc123 s2 = abcdef
输出返回一个1,实际上应该是a-1,因为s1中的字符'1‘比s2中的'd’值要低。
发布于 2021-03-02 08:35:20
您提供给我们的程序并不是您真正使用的程序,因为它没有编译,因此缺少一个;。我想它是在递归rStrcmp调用之后出现的。
你应该激活你的编译器的警告,你会发现
In function ‘rStrcmp’: .code.tio.c:60:1: warning: control reaches end of non-void function [-Wreturn-type] }
实际上,在函数rStrcmp中,递归行应该是:
...
else // recursive condition
{
return rStrcmp(s1+1,s2+1); /* the return was missing here */
}
...正如注释中所指出的,您可以通过删除else来简化代码,因为返回之后,您就不再在函数中了:
int rStrcmp(char *s1, char *s2)
{
// The terminating conditions:
if (*s1 == '\0' && *s2 == '\0') // both strings end together
return 0;
if (*s1 == '\0') // s1 ends first (s1 smaller)
return ‐1;
if (*s2 == '\0') // s2 ends first (s1 larger)
return 1;
if (*s1 < *s2) // ASCII char in s1 < s2 : (s1 smaller)
return ‐1;
if (*s1 > *s2) // ASCII char in s1 > s2 : (s1 larger)
return 1;
// recursive condition
return rStrcmp(s1+1,s2+1); // moves the address to point to the next char
}最后一步,您可以在main函数中添加一些格式化信息,以获得更好的输出:
result = rStrcmp(source, target);
printf("rStrcmp(): %d\n", result);
printf("'%s' %c '%s'\n", source, result == 0 ? '=' : result < 0 ? '<' : '>' , target);https://stackoverflow.com/questions/66435441
复制相似问题