酷代码 AI
菜单

7-1 统计单词数 分数 10 作者 陈宇璟 单位 浙江大学 一般的文本编辑器都有查找单词的功能,该功能可以快速定位特定单词在文章中的位置,有的还能统计出特定单词在文章中出现的次数。 现在,请你编程实现这一功能,具体要求是:给定一个单词,请你输出它在给定的文章中出现的次数和第一次出现的位置。注意:匹配单词时,不区分大小写,但要求完全匹配,即给定单词必须与文章中的某一独立单词在不区分大小写的情况下完全相同(参见样例 1),如果给定单词仅是文章中某一单词的一部分则不算匹配(参见样例 2)。 输入格式 共 2 行。 第 1 行为一个字符串,其中只含字母,表示给定单词; 第 2 行为一个字符串,其中只可能包含字母和空格,表示给定的文章。 输出格式 一行,如果在文章中找到给定单词则输出两个整数,两个整数之间用一个空格隔开,分别是单词在文章中出现的次数和第一次出现的位置(即在文章中第一次出现时,单词首字母在文章中的位置,位置从 $$ 开始);如果单词在文章中没有出现,则直接输出一个整数 -1。 注意:空格占一个字母位 输入样例: To to be or not to be is a

```cpp #include <iostream> #include <sstream> #include <string> #include <cctype> #include <vector> // 将字符串转换为小写 std::string toLowerCase(const std::string& str) { std::string result = str; for (char& c : result) { c = std::tolower(c); } return result; } int main() { std::string target; std::getline(std::cin, target); target = toLowerCase(target); std::string article; std::getline(std::cin, article); std::stringstream ss(article); std::vector<std::string> words; std::string word; while (ss >> word) { words.push_back(word); } int count = 0; int firstPos = -1; int currentPos = 0; for (size_t i = 0; i < words.size(); ++i) { std::string lowerWord = toLowerCase(words[i]); if (lowerWord == target) { if (count == 0) { for (size_t j = 0; j < i; ++j) { currentPos += words[j].length() + 1; } firstPos = currentPos; } ++count; } } if (count > 0) { std::cout << count << " " << firstPos << std::endl; } else { std::cout << -1 << std::endl; } return 0; } ``` 代码解释 1. toLowerCase函数:该函数用于将输入的字符串转换为小写形式,通过遍历字符串中的每个字符,使用`std::tolower`函数将字符转换为小写。 2. 主函数: - 首先使用`std::getline`读取目标单词,并将其转换为小写。 - 接着读取文章字符串,并使用`std::stringstream`将文章按空格分割成单词,存储在`std::vector`中。 - 然后遍历存储单词的向量,将每个单词转换为小写并与目标单词比较。 - 如果找到匹配的单词,若这是第一次匹配,则计算该单词在文章中的起始位置。 - 最后根据匹配情况输出结果,若有匹配则输出匹配次数和首次出现位置,否则输出 -1。 [2025-12-15 17:26:33 | AI问答 | 570点数解答]

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