C - 使用二维数组存储多个字符串



我用 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 numbersn");
    printf("Enter a number to search: ");
    scanf("%s", s1);
    for(int i  = 0; i < counter; i++){
        printf("%d : %sn", 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 !='';)
    {
        if(*s2=='')
            break;
        for(;*s2 !='';)
        {
            if(*s1==*s2)
            {
                f=1;
                s1 ++;
                s2 ++;
            }
            else
            {
                f=0;
                s1++;
                break;
            }
        }
    }
    if(f==0)
        return 0;
    else
        return 1;
    getch();
}

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

int substring(const char *s1, const char *s2)
{
    enum
    {
        search, start_match
    } state = search;
    const char *m;
    while(*s1 != '')
    {
        switch(state)
        {
        case search:
            if(*s2 == '')
                return 0;
            else if(*s2 == *s1)
            {
                state = start_match;
                m = s2 + 1;
            }
            break;
        case start_match:
            if(*m == '')
                return 1;
            else if(*m != *s1)
                state = search;
            else
                ++m;
        }
        ++s1;
    }
    return 0;
}

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

相关内容

  • 没有找到相关文章

最新更新