【问题标题】:Why is std::reverse() not reversing the string?为什么 std::reverse() 不反转字符串?
【发布时间】:2021-12-08 02:34:01
【问题描述】:

我正在尝试逐字反转输入的句子。例如:

输入:这是一个句子

输出应该是:

输出:句子 a is This

所以我在以下代码中使用字符串:

#include <iostream>
#include <string>
#include <cstring>
#include <algorithm>

int main()
{
    

        std::string sentence("This is a sentence"), rev_sentence;
        char *words = new char[20];
        
        std::cout <<"This is the sentence : "<< sentence << std::endl;
        
        words = strtok(&sentence[0], " "); //Tokenizing
        while (words != NULL)
        {
            rev_sentence.append(words);
            rev_sentence += ' ';
            words = strtok(NULL, " ");
        }
        rev_sentence.pop_back(); //Removing the last blankspace
        
        std::cout <<"This is before final reverse : " << rev_sentence << std::endl;
        
        std::reverse(rev_sentence.begin(), rev_sentence.end()); //reverse()
        std::cout << rev_sentence << std::endl;
    return 0;
}

std::reverse() 之前的输出很好,但是一旦我调用它,它就不会打印最终输出。 谁能指出我做错了什么?

【问题讨论】:

  • 您的示例泄漏了内存。我建议避免拥有裸指针。
  • 考虑这一点:如果您构建“一二三”,则将其反转为 字符 序列的结果是“eerht owt eno”,而不是“三二一”。如果您想反转单词,请执行此操作;不是整个字符串。有多种方法可以做到这一点,最简单的是将单词读入字符串的双端队列,将每个单词推到前面,然后在完成后枚举双端队列。祝你好运。
  • 这并不能解决问题,但不要与strtok 混淆。这是可憎的。 std::string 具有丰富的成员函数集,用于搜索字符串的内容。

标签: c++ string reverse


【解决方案1】:

您正在尝试反转字符串的字符,因为 std::string rev_sentence 的元素是字符。

使用带有字符串元素的容器,例如 std::vector&lt;std::string&gt; 作为反向源。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-04-22
    • 2012-04-26
    • 2017-10-29
    • 2014-10-06
    • 2021-11-06
    • 2013-01-26
    • 2022-10-05
    • 1970-01-01
    相关资源
    最近更新 更多