我正在某种模式下在字符串中搜索作业。在测试代码时,我声明了一个默认值以便于测试。当我完成测试并尝试使用用户输入来运行代码时,输出将有所不同。 输出(使用默认值时)“在位置4处匹配”。但是当使用用户输入时,它会显示“ no match”。
这是我的代码:
int main() {
char text[255],pattern[255];
char sensitive = 'N';
int n,a[255],i,j,k = 0,l,found = 0,t = 0,temp=0;
printf("Enter a sentence,up to 255 characters:");
fgets(text,255,stdin);
text[strcspn(text,"\n")] = 0;
printf("Enter a pattern,up to 255 characters:");
fgets(pattern,stdin);
pattern[strcspn(pattern,"\n")] = 0;
printf("Should the match be case-sensitive,Y or N?");
scanf("%c",&sensitive);
if (sensitive == 'N' || sensitive == 'n') {
for (i = 0; i < strlen(text); i++) {
text[i] = tolower(text[i]);
//printf("%c",text[i]);
}
for (i = 0; i < strlen(pattern); i++) {
pattern[i] = tolower(pattern[i]);
//printf("%c",pattern[i]);
}
}
for (i = 0;text[i] != '\0';i++)
{
j = 0;
if (text[i] == pattern[j] || pattern[j] == '.')
{
temp = i + 1;
while (text[i] == pattern[j] || pattern[j] == '.')
{
i++;
j++;
}
if (pattern[j] == '\0')
{
temp -= 1;
printf("Matches at position %d\n",temp);
exit(0);
}
else
{
i = temp;
temp = 0;
}
}
}
if (temp == 0)
printf("No match.\n");
return 0;
}