我是一名C语言新手。 我的老师说我们必须写一个项目来: 在第一个字符串中查找没有任何指针(*)的第二个字符串。到目前为止,我已经学习了循环、条件、函数和数组,它们是我唯一的选择。 该项目必须从两个级别的用户那里获取字符串。检查它们并打印结果。
现在我已经写了一些废话:
int main()
{
char source[MAX_STR_LEN];
char target[MAX_STR_LEN];
int len = 50;
int a;
scanf("%s", &source);
scanf("%s", &target);
for (int i = 0; i <= len; i++)
{
if (strncasecmp(source[i], target[i], strlen(target)) == 0)
{
int a = 1;
if (a == 1)
{
printf("%s is inner of %s", target, source);
}
else
{
printf("%s is NOT inner of %s", target, source);
}
}
}
return 0;
}
但是当我输入两个字符串时,我的项目不打印任何内容并自动关闭。我确信我的代码不正确,有什么简单的方法可以做到这一点吗? 谢谢
最佳答案
首先你要改进如何在原始字符串中查找子字符串的逻辑,或者如果老师允许你可以离开C语言来查找它。
strstr 正在做这项工作。
下面是我的代码,我在您的代码中添加了注释
#include <stdio.h>
#include <strings.h>
#define MAX_STR_LEN 50
int main(void)
{
char source[MAX_STR_LEN];
char target[MAX_STR_LEN];
//int len = 50;
//int a;
scanf(" %s", source); //char array name is used like pointer to the first element of array
scanf(" %s", target);
char* ret = NULL;
ret = strstr(source, target);
if(ret == NULL)
printf("%s is NOT inner of %s", target, source);
else
printf("%s is inner of %s", target, source);
return 0;
}
关于c - 在C中没有指针的情况下在第二个字符串中查找第一个字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55182610/