在第二个字符串中查找第一个字符串,而不在 C 中查找指针



我是一名新手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 语言进行搜索。

斯特斯特做这项工作。

下面是我的代码,我在您的代码中添加了注释

#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;
}

一个非常简单的方法是逐个字符检查源字符串以查看是否找到目标字符串。换句话说:

  • 从源[0]开始检查目标字符串是否存在。
  • 如果不是:从源代码[1]开始检查目标字符串是否存在。
  • 如果不是:从源代码[2]开始检查目标字符串是否存在。
  • 依此类推,直到到达源字符串的末尾。

这可以使用两个 for 循环来完成,其中外部循环迭代源字符串中的所有字符,内部循环迭代目标字符串,同时比较两个字符串中的字符。

您可以像这样可视化它:

source: Hello World
target: lo
Hello World
lo           // No match: He != lo
Hello World
lo          // No match: el != lo
Hello World
lo         // No match: ll != lo
Hello World
lo        // Match: lo != lo

一个简单的实现可能如下所示:

int main()
{
char source[MAX_STR_LEN] = "Hello World";
char target[MAX_STR_LEN] = "lo";
int source_index = 0;
int match = 0;
while (source[source_index] != '')
{
int target_index = 0;
while (target[target_index] != '' &&
source[source_index + target_index] != '' && 
source[source_index + target_index] == target[target_index])
{
++target_index;
if (target[target_index] == '')
{
match = 1;
break;
}
}
if (match) break;
++ source_index;
}
if (match)
{
printf("foundn");
}
else
{
printf("not foundn");
}
return 0;
}

兄弟,您分配的值为int a = 1;并在检查if(a == 1)后立即没有任何意义else{printf("%s is NOT inner of %s", target, source);}因为上述部分代码将永远不会在这种情况下使用,这是 https://www.geeksforgeeks.org/given-two-strings-find-first-string-subsequence-second/be 小心:)

的解决方案

最新更新