《C How to Program》8.16题子串查找代码运行异常排查
问题原因
你代码存在两个核心问题:
- 第一:
fgets函数读取用户输入时,会把输入结束时按下的回车对应的\n换行符一并存入字符串,导致你实际用于搜索的search_string末尾多了一个换行符,和文本里的world无法正常匹配,自然找不到第二次出现的位置。 - 第二:找到匹配的子串后,你只打印了提示文本,没有打印
searchPtr指向的剩余文本,不符合题目要求的输出规则。
修复方案
首先需要把fgets读取到的字符串末尾的换行符去掉,再执行搜索逻辑,同时补全剩余文本的输出。
修复后的完整代码如下:
#include <stdio.h> #include <string.h> #define SIZE 128 int main(void){ char s[SIZE], search_string[SIZE]; char *searchPtr; // 读取输入并去除末尾换行符 fgets(s, SIZE, stdin); s[strcspn(s, "\n")] = '\0'; fgets(search_string, SIZE, stdin); search_string[strcspn(search_string, "\n")] = '\0'; searchPtr = strstr(s, search_string); if(searchPtr){ printf("The text line beginning with the first occurrence of %s: %s\n", search_string, searchPtr); // 找第二次出现的位置 searchPtr = strstr(searchPtr + 1, search_string); if(searchPtr){ printf("The text line beginning with the second occurrence of %s: %s\n", search_string, searchPtr); } else{ printf("The string to be searched just appeared once.\n"); } } else { printf("Search string is not found in the string."); } return 0; }
修复验证
输入测试用例:
第一行输入hello world world,第二行输入world,输出如下:
The text line beginning with the first occurrence of world: world world The text line beginning with the second occurrence of world: world
完全符合题目预期要求。
内容的提问来源于stack exchange,提问作者akoluacik
相关产品推荐
相关产品推荐

