0

我在 C 中编写了一个函数,用于搜索子字符串是否在字符串中并且没问题,但是当我在字符串数组中使用它时,我遇到了错误。请看这段代码:

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

int substring(char*, char*);

main()
{
    char student[100][7];
    int counter = 0;
    int finish =1;
    char s1[4];
    while(finish){
        printf("please Enter Student Number: \n");
        scanf("%s", student[counter]);
        counter++;
        printf("Do you want to exit? 1/0");
        scanf("%d", &finish);
    }
    printf("Now, You can search in Student numbers\n");
    printf("Enter a number to search: ");
    scanf("%s", s1);
    for(int i  = 0; i < counter; i++){
        printf("%d : %s\n", i, student[i]);
        if(substring(student[i],s1) == 1)
            printf("%s", student[i]);
    }

    getch();
}

int substring(char *s1,char *s2)
{
    int f=0;
    for(; *s1 !='\0';)
    {
        if(*s2=='\0')
            break;
        for(;*s2 !='\0';)
        {
            if(*s1==*s2)
            {
                f=1;
                s1 ++;
                s2 ++;
            }
            else
            {
                f=0;
                s1++;
                break;
            }
        }
    }
    if(f==0)
        return 0;
    else
        return 1;
    getch();
}
4

1 回答 1

0

这是使用简单状态机测试子字符串的方法:

int substring(const char *s1, const char *s2)
{
    enum
    {
        search, start_match
    } state = search;
    const char *m;

    while(*s1 != '\0')
    {
        switch(state)
        {
        case search:
            if(*s2 == '\0')
                return 0;
            else if(*s2 == *s1)
            {
                state = start_match;
                m = s2 + 1;
            }
            break;
        case start_match:
            if(*m == '\0')
                return 1;
            else if(*m != *s1)
                state = search;
            else
                ++m;
        }

        ++s1;
    }

    return 0;
}

您也可以使用标准的strstr函数。

于 2013-01-26T16:01:47.127 回答