gpt4 book ai didi

c++ - 颠倒句子中单词的顺序

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:06:20 24 4
gpt4 key购买 nike

#include <iostream>
#include <cstring>
using namespace std;
void reverse(char* sentence)
{
int index = strlen(sentence) - 1;
char last = '\0';
int hold = 0;
while ( index != 0){
while (sentence[index] != ' ')
index--;
hold = index; //keeps the index of whitespace
while (sentence[index] != last){
cout << sentence[index]; //printing till it either hits end character or whitespace.
index++;
}
last = sentence[hold]; //Keeps the whitespace
index = hold; //
}

}
int main()
{
char* sentence = new char[256];
cin.getline(sentence, 256);
reverse(sentence);
}

我想颠倒句子中的单词顺序,你可以在上面看到我的尝试。

示例输入和输出应该是这样的:

Howdy Mr. Mcfly? 

Mcfly? Mr. Howdy

我在哪里:

Howdy Mr. Mcfly?
Mcfly?

互联网上有很多类似的问题,但我想要的是在我自己的代码中查找错误。

最佳答案

您可以使用 std::string std::vectorstd::reverse 让事情变得更简单:

std::string sentence = "Your sentence which contains ten words, two of them numbers";
std::stringstream stream(sentence);
std::vector<std::string> words;
for ( std::string word; stream >> word; )
{
words.push_back(word);
}

现在你把所有的东西都分成了单词。您现在可能想要删除问号或其他标点符号,因为在单词仍处于正确顺序时逻辑将更容易实现。要反转,请执行以下操作:

std::reverse(words.begin(), word.end());

您需要包含多个 header :

#include <string> // for storing strings in a C++ way
#include <sstream> // to easily separate sentences into words
#include <vector> // to dynamically store arbitrary amounts of words
#include <algorithm> // for std::reverse

您可以看到此代码与此 demo on ideone.com 一起运行

关于c++ - 颠倒句子中单词的顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17026740/

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