酷代码 AI
菜单
服务商
DeepSeek字节豆包讯飞星火
更多选项

C++ 实现字符串单词统计:代码示例及三大改进建议

以下是一个用 C++ 实现统计输入字符串中单词个数的示例代码: ```cpp #include <iostream> #include <string> int countWords(std::string str) { int count = 0; bool inWord = false; for (char c : str) { if (c =='') { if (inWord) { count++; } inWord = false; } else { inWord = true; } } if (inWord) { count++; } return count; } int main() { std::string input; std::cout << "请输入字符串: "; std::getline(std::cin, input); int wordCount = countWords(input); std::cout << "单词个数为: " << wordCount << std::endl; return 0; } ``` 以下是三个改进建议: 1. 可以添加对输入字符串的合法性检查,例如是否为空字符串。 2. 考虑使用更高效的数据结构,如 `std::vector` 来存储单词。 3. 对代码添加更多的注释,以提高代码的可读性。 ######[AI写代码神器 | 278点数解答 | 2024-12-28 16:20:30]

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