【问题标题】:How do I know if a string is contained within the another?我如何知道一个字符串是否包含在另一个字符串中?
【发布时间】:2021-08-05 14:28:57
【问题描述】:

假设用户在我的程序中输入了一个字符串,我希望我的程序将字符串的某个部分与我已有的字符串进行比较。例如:

用户输入:“你好,我做得很好”。

我要查找的字符串部分是“做得很好”。

C 编程语言中是否有任何特定的方式或功能可以帮助我做到这一点?

【问题讨论】:

  • 标准库函数strstr可以做到这一点。
  • 您应该真正编辑您的问题及其标题,以便(也对您自己)阐明您的需求。您不想“仅将字符串的一部分与另一个字符串进行比较”,因为这表明您已经知道要比较的部分。你想要的是找到 if 一个字符串包含在另一个字符串中,以及它是否在它所在的位置。
  • 学习一门新语言及其环境包括阅读大量文档。一本好的初学者的 C 书或标准很有帮助,也在这里。
  • 如果您无法使用@SteveSummit 建议的功能,请编辑您的问题并提供minimal reproducible example。写作是学习语言的好方法。

标签: c string compare


【解决方案1】:

你可以试试。

char your_sentence[512] = "Hello I'm doing great";
char looking_for[256]= "doing great";
char *result = strstr(your_sentence, looking_for);
if(result != NULL)
    printf(result);
else
    printf("not found!");

请为您的字符串选择合适的长度!

【讨论】:

  • "请为您的字符串选择合适的长度!" --> 让编译器用char your_sentence[/*nothing here*/] = "Hello I'm doing great";来做
【解决方案2】:

,

#include <stdio.h>

#include <string.h>

int main()
{
    char user_input[1000];
    scanf("%[^\n]%*c",user_input);
   
    char search[] = "doing great";
    char *ptr = strstr(user_input, search);

    if (ptr != NULL) /* Substring found */
        {
        printf("'%s' contains '%s'\n", user_input, search);
        }
        else /* Substring not found */
        {
            printf("'%s' doesn't contain '%s'\n", user_input, search);
        }

    

return 0;

}

【讨论】:

    猜你喜欢
    • 2021-05-06
    • 2011-02-05
    • 2013-03-13
    • 1970-01-01
    • 2014-10-08
    • 2014-07-24
    • 1970-01-01
    • 2014-04-14
    相关资源
    最近更新 更多