【问题标题】:Searching a string inside another string在另一个字符串中搜索一个字符串
【发布时间】:2021-11-28 00:47:50
【问题描述】:

我想写一个这样工作的程序:

1:接收string1和string2

2:比较两者的长度,看看哪个更小

3:检查较小的字符串是否在较大的字符串中使用

现在我知道如何编写第 1 步和第 2 步,但我不知道如何解决第 3 步:/

到目前为止,这是我的代码:

#include <stdlib.h>
#include <stdio.h>
#include <string.h>
    
    
int main()
{
    printf("Please enter string 1 size and then enter a text: ");
    int size1;
    scanf("%d", &size1);
    char test1[size1];
    scanf("%s", test1);
   
    printf("Please enter string 2 size and then enter a text: ");
    int size2;
    scanf("%d", &size2);
    char test2[size2];
    scanf("%s", test2);
    
    int test1_len = strlen(test1);
    int test2_len = strlen(test2);
    
    if (test1_len < test2_len)
    {
        //searching test1 in test2
    }
    else //(test1_len >= test2_len)
    {
        //searching test2 in test1
    }
    
    return 0;
}

【问题讨论】:

  • 这里有很多关于做这种事情的问题。在这个网站上搜索短语[c] find substring in a string
  • 使用后输入和预期输出。

标签: c


【解决方案1】:

类似问题的应用答案: Simple way to check if a string contains another string in C? 提供的示例。

还添加了字符串长度和内容匹配的附加情况。

#include <stdlib.h>
#include <stdio.h>
#include <string.h>

int main()
{
    printf("Please enter string 1 size and then enter a text: ");
    int size1;
    scanf("%d", &size1);
    char test1[size1];
    scanf("%S", test1);

    printf("Please enter string 2 size and then enter a text: ");
    int size2;
    scanf("%d", &size2);
    char test2[size2];
    scanf("%S", test2);

    int test1_len = strlen(test1);
    int test2_len = strlen(test2);

    if (test1_len < test2_len)
    {
        printf("String1 length is less than String2 length");

        if (strstr(test2, test1) != NULL) {
            printf("String1 is in String2");
        } 
        else {
            printf("String1 is not in string2");
        }
    }
    else if (test1_len > test2_len)
    {
        printf("String2 length is less than String1 length");
        
        if (strstr(test1, test2) != NULL) {
            printf("String2 is in string1");
        }
        else {
            printf("String2 is not in string1");
        }
    }
    else 
    {
        printf("String1 and String2 are same length");
        
        if (strstr(test1, test2) != NULL) {
            printf("String1 and String2 are the same");
        }
        else {
            printf("String1 and String2 are not the same");
        }
    }

    return 0;
}

【讨论】:

  • 最好添加解释为什么会这样,而不是吐出一大堆没有解释的代码。
  • 你能翻译一下这行吗? "strstr(test2, test1) != NULL" 这是我没有得到的部分
  • 'scanf("%S", test1);'中的大写'S'是小姐类型。可能是不小心写错了,抄的时候没注意。如果代码完整,我会在没有得到合适的结果后修复它,但感谢@chux
猜你喜欢
  • 2013-01-18
  • 1970-01-01
  • 1970-01-01
  • 2012-03-05
  • 2015-02-07
  • 1970-01-01
  • 2013-08-08
  • 1970-01-01
相关资源
最近更新 更多