gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 17:55:05 25 4
gpt4 key购买 nike

我用 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();
}

最佳答案

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

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功能。

关于c - 使用二维数组存储多个字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14538422/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com