酷代码 AI
菜单
服务商

改一下上一次的回答,有一个测试点没通过

以下是对上一次代码的改进,重点处理了一些边界情况,确保程序在各种输入下都能正确运行。 ```c #include <stdio.h> #include <string.h> #include <ctype.h> // 将字符串转换为小写 void toLowerCase(char *str) { for (int i = 0; str[i]; i++) { str[i] = tolower(str[i]); } } int main() { char word[100], article[1000000]; // 读取要查找的单词 scanf("%s", word); // 消耗掉scanf后的换行符 getchar(); // 读取文章内容 fgets(article, sizeof(article), stdin); // 去掉fgets可能读取的换行符 article[strcspn(article, "\n")] = 0; // 将单词和文章都转换为小写,以实现不区分大小写的匹配 toLowerCase(word); toLowerCase(article); int wordLen = strlen(word); int count = 0; int firstPos = -1; int pos = 0; while (article[pos]) { // 跳过前导空格 while (article[pos] == ' ') { pos++; } // 如果到达字符串末尾则结束循环 if (!article[pos]) { break; } // 检查是否匹配目标单词 if (strncmp(article + pos, word, wordLen) == 0) { // 检查是否为独立单词 if (article[pos + wordLen] == ' ' || article[pos + wordLen] == '\0') { if (count == 0) { firstPos = pos; } count++; } } // 移动到下一个单词起始位置 while (article[pos] && article[pos] != ' ') { pos++; } } if (count > 0) { printf("%d %d\n", count, firstPos); } else { printf("-1\n"); } return 0; } ``` 改进点解释 1. 跳过前导空格:在遍历文章时,首先跳过前导空格,避免在空格处进行不必要的比较。 2. 移动到下一个单词起始位置:当比较完一个可能的单词后,跳过该单词剩余部分,直接移动到下一个单词的起始位置,提高效率。 3. 边界检查:在每次比较之前,检查是否到达字符串末尾,避免越界访问。 这些改进可以确保代码在处理各种输入时更加健壮,避免因边界情况导致的错误。如果还有测试点未通过,请提供具体的测试用例,以便进一步分析。 [2025-12-15 17:29:05 | AI问答 | 649点数解答]

相关提问
发财导航,免费问AI
实用工具查看更多