c - 在C中没有指针的情况下在第二个字符串中查找第一个字符串

标签 c string pointers

我是一名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/

相关文章:

c - 数组 : error variably modified 的 C 错误

java - 正则表达式捕获 Java 中的所有单词和 "i' m you’re 等

python - 如何在 Python 中打印不包含 '\n' 的字符串

c - 从指向嵌套结构的指针访问元素

c - 释放它们后真的应该将指针设置为 `NULL` 吗?

使用 getchar() 在 C 中计算数学表达式

cURL C 教程

c - 使用 sscanf 解析不会保留数组以供后续使用

java - 使用来自循环方法的列表内容更新列表

c - 免费如何知道要免费多少?