简体   繁体   English

为什么 std::reverse() 不反转字符串?

[英]Why is std::reverse() not reversing the string?

I am trying to reverse an input sentence word by word.我正在尝试逐字反转输入句子。 For example :例如 :

Input : This is a sentence输入:这是一个句子

The output should be :输出应该是:

Output : sentence a is This输出:句子 a is This

So I am using strings in the following code :所以我在以下代码中使用字符串:

#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;
}

The output is fine before std::reverse() but it does not print the final output once I call it.std::reverse()之前输出很好,但是一旦我调用它就不会打印最终输出。 Can anyone specify what I am doing wrong?任何人都可以指定我做错了什么吗?

You are trying to reverse the characters of a string, as element of std::string rev_sentence are characters.您正在尝试反转字符串的字符,因为std::string rev_sentence元素是字符。

Use a container with string elements, like std::vector<std::string> as the source for reverse.使用带有字符串元素的容器,例如std::vector<std::string>作为反向源。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM