gpt4 book ai didi

c++:我正在尝试颠倒字符串中单词的顺序(不是整个字符串)

转载 作者:太空宇宙 更新时间:2023-11-04 15:52:02 24 4
gpt4 key购买 nike

#include <iostream>
#include <vector>
using namespace std;

void RevStr (char *str)
{
if(*str !=0)
{
vector<char> v1;

while((*str != ' ')&&(*str !=0))
v1.push_back(*str++);
// trying to not add space in the last word of string
if(*str !=0)
{
v1.push_back(' ');
str++;
}
RevStr(str);
cout<<*str;
}


}
int main()
{
RevStr("hello world!");
cout<<endl;

}

我想改变字符串中单词的顺序,例如“你好吗”=>“你怎么样”

我遇到了一些问题,打印不正确(只打印 w),请帮助我并告诉我我做错了什么。但是我知道我不应该调用“cout<<*str;"因为我在堆栈(递归)中插入了“char 数组”,但我不知道我需要做什么。

最佳答案

C++ 使它变得简单:

#include <algorithm>
#include <iterator>
#include <vector>
#include <string>
#include <iostream>
#include <sstream>

std::string reverse(std::string const& text)
{
std::stringstream inStream(text);
std::stringstream outStream;
std::vector<std::string> words;

std::copy(std::istream_iterator<std::string>(inStream), std::istream_iterator<std::string>(), std::back_inserter(words));
std::copy(words.rbegin(), words.rend(), std::ostream_iterator<std::string>(outStream, " "));
return outStream.str();
}


int main()
{
std::cout << reverse("Hello World") << "\n";
}

关于c++:我正在尝试颠倒字符串中单词的顺序(不是整个字符串),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6336392/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com