【发布时间】:2020-06-17 18:18:18
【问题描述】:
我有一个程序可以正确匹配输入字符串中的搜索字符串(以一个点开头),但不适用于两个或更多点。
主要功能:
int main()
{
int position;
char input[255], pattern[255];
printf("Please enter a line of text of up to 255 characters:\n");
fgets(input,sizeof(input),stdin);
input[strcspn(input, "\n")] = 0;
printf("Please enter the search text of up to 255 characters:\n");
fgets(pattern,sizeof(pattern),stdin);
pattern[strcspn(pattern, "\n")] = 0;
cmp(input, pattern);
return 0;
}
cmp函数:
char cmp(char input[],char pattern[])
{
int i, pattern_position, input_position;
for(int pattern_position = 0; pattern_position < strlen(pattern); pattern_position++) {
if(pattern[pattern_position] == '.'){
char letter_space_comma[54] = {'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', ',', ' ', 'a', 'b', 'c', 'd', 'e', 'f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'};
for (int letter_space_comma_position= 0; letter_space_comma_position < 54; letter_space_comma_position++){
pattern[pattern_position] = letter_space_comma[letter_space_comma_position];
char *pos = strstr(input, pattern);
if (pos) {
printf("Matches at position %ld.", pos-input);
goto end;
}
}
}
}
char *pos = strstr(input, pattern);
if (pos) {
printf("Matches at position %ld.", pos-input);
} else {
printf("No match.");
}
end:
return 0;
}
输入 1(1 个点):
Please enter a line of text of up to 255 characters: The cat sat on the mat.
Please enter the search text of up to 255 characters: .at
输出 1(正确):
Matches at position 4.
输入 2(3 个点):
Please enter a line of text of up to 255 characters: The cat sat on the mat.
Please enter the search text of up to 255 characters: ...
我的输出 2:
No match.
预期输出 2:
Matches at position 0.
【问题讨论】:
-
这似乎是学习如何使用调试器的好时机。使用调试器,您可以在监视变量及其值的同时逐句执行代码。这样可以很容易地查看出现问题的时间和地点。
标签: c pattern-matching