酷代码 AI
菜单
服务商

编程实现:统计特定单词在文章中出现次数与首次位置(附代码及详细解释)

```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。 ######[AI问答 | 570点数解答 | 2025-12-15 17:26:33]

相关提问
本站限时免费提问中
实用工具查看更多
Linux在线手册 [开发类]
Jquery在线手册 [开发类]
今日油价 [生活类]
图片互转base64 [开发类]
时间转换器 [开发类]