为什么C++中调用std::reverse()未按预期反转字符串?
问题原因
- 核心逻辑错误:你当前的实现逻辑是将原句按单词拆分后,仍然按原顺序拼接成和原句完全一致的字符串,再直接反转整个字符串。这会导致不仅单词顺序被反转,每个单词内部的字符也被全部反转,自然拿不到预期结果。比如你拼接后得到的
rev_sentence在反转前就是This is a sentence,整体反转后会变成ecnetnes a si sihT,和预期输出不符。 - 无用代码+内存泄漏:开头
char *words = new char[20];申请的堆内存完全没有被使用,后续你直接将strtok的返回值赋值给words指针,导致申请的内存地址丢失,没有释放造成泄漏。 - 不安全操作:
strtok会修改传入的字符串内容,直接传入std::string的内部指针&sentence[0]会修改原string的存储内容,属于非预期的不安全操作。
修正实现
你可以选择两种常用实现思路,下面给出更符合C++规范的实现,不用C风格的strtok:
#include <iostream> #include <string> #include <vector> #include <sstream> #include <algorithm> int main() { std::string sentence("This is a sentence"); std::cout << "This is the sentence : " << sentence << std::endl; // 拆分单词存入vector std::vector<std::string> words; std::stringstream ss(sentence); std::string word; while (ss >> word) { words.push_back(word); } // 倒序拼接单词 std::string rev_sentence; for (auto it = words.rbegin(); it != words.rend(); ++it) { if (!rev_sentence.empty()) { rev_sentence += ' '; } rev_sentence += *it; } std::cout << rev_sentence << std::endl; return 0; }
如果坚持用先反转整体再反转单个单词的思路,也可以按如下实现:
#include <iostream> #include <string> #include <algorithm> int main() { std::string sentence("This is a sentence"); std::cout << "This is the sentence : " << sentence << std::endl; // 先反转整个字符串 std::reverse(sentence.begin(), sentence.end()); // 再逐个反转每个单词 size_t start = 0; for (size_t i = 0; i <= sentence.size(); ++i) { if (i == sentence.size() || sentence[i] == ' ') { std::reverse(sentence.begin() + start, sentence.begin() + i); start = i + 1; } } std::cout << sentence << std::endl; return 0; }
内容的提问来源于stack exchange,提问作者Priyanshu
相关产品推荐
相关产品推荐

