c - 7 个测试用例中有 1 个不能使用这个简单的 C 程序来查找子字符串

标签 c string substring

我接到一项任务,要编写一个 C 程序来查找包含 7 个测试用例的子字符串。我写了这个程序,但它只通过了 6 个测试用例。第 7 个失败了,我无法确定其背后的原因。

编辑:这是我在作业中遇到的问题。

Write a program that takes two input strings S1 and S2 and finds if S2 is a substring of S1 or not. If S2 is a substring of S1, the program should print the index at S1 at which there is a match. If S2 is not a substring of S1, the program should print -1. If S2 appears in S1 multiple times, print the first index in S1 at which the match occurred.

这是我编写的程序的源代码。

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

int main() {
    char st1[19];
    char st2[19];
    int cnt,i,k,c,len,m,sign;
    scanf("%s %s", st1, st2);
    len=strlen(st1);
    for(i=0; i<len; i++) {
        c=0;
        if (st1[i] == st2[c]) {
            m = i;
            sign = 0;
            cnt = 0;
            while(st2[c] != '\0' && sign!=1) {
                if (st1[m] == st2[c]) {
                    m++;
                    c++;
                    cnt++;
                } else
                    sign=1;
            }
            if (sign == 0) {
                printf("%d",i);
                k=1;
            }
        }
    }
    if (k != 1)
        if (sign!=0)
            printf("-1");
    return 0;
}

第7个测试用例如下

输入:

coolgoose oo

预期输出:

1

实际输出:

15

编辑 2:这是通过的其他测试用例。

Input       Output

football foot   0

mickey mouse    -1

abcdefghijklmnopqrs s   18

helloworld helloworld   0

FrodoBaggins bagg   -1

Hell Hello  -1

最佳答案

它实际上打印它找到的每个匹配项:在字符 1 和字符 5 处。当找到匹配项时,您应该break 退出 for 循环。

关于c - 7 个测试用例中有 1 个不能使用这个简单的 C 程序来查找子字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22581840/

相关文章:

android - 如何在Android中获取子字符串?

c - 是什么让 D 成为一门好语言?

java - C转java文件读取和打印

c++ - C/C++中固定大小栈的树遍历

来自字符串的 Javascript 嵌套对象

php - 通过php查找字符串中第一次出现的数字位置

javascript - 从文本中获取两个特定字符序列之间的子字符串

python - Pandas:通过在列中查找子字符串改进算法

c - C 中的 HTTP POST 使用域名而不是 IP

java - 在jsp页面中插入的特殊字符和中文字体在spring Controller 中不起作用