#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);
}
Run Code Online (Sandbox Code Playgroud)
我想颠倒句子中的单词顺序,你可以看到我的上述尝试.
示例输入和输出应该是这样的:
Howdy Mr. Mcfly?
Mcfly? Mr. Howdy
Run Code Online (Sandbox Code Playgroud)
我得到的地方:
Howdy Mr. Mcfly?
Mcfly?
Run Code Online (Sandbox Code Playgroud)
互联网上有许多类似的问题,但我想要的是在我自己的代码中找到错误.
ste*_*fan 11
您可以使用std::string std::vector并std::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);
}
Run Code Online (Sandbox Code Playgroud)
现在你把所有东西分成了单词.您现在可能想要删除问号或其他标点符号,因为在单词仍处于正确顺序时,逻辑将更容易实现.对于倒车,请执行以下操作:
std::reverse(words.begin(), word.end());
Run Code Online (Sandbox Code Playgroud)
您需要包含多个标头:
#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
Run Code Online (Sandbox Code Playgroud)
您可以在ideone.com上使用此演示查看此代码
正如其他答案建议您应该使用std::string它可以节省很多麻烦。但只是为了注释,
void reverse(char* sentence)
{
int index = strlen(sentence) - 1,hold,last = '\0';
/*For the 1st iteration last is `\0` for all others it is ` `*/
while (index >= 0)
{
/*
In your original code,
This while loop(below) will continue to keep decrementing index
even below `0`,You wont exit this while loop until you encounter a ` `.
For the 1st word of the sentence you will never come out of the loop.
Hence the check, index>=0
*/
while (index>=0 && sentence[index] != ' ')
index--;
/* You can print the whitespace later*/
hold = index - 1; // This keeps track of the last character
// of preceding word
index++; //character after space
while (sentence[index] != last)
{
cout << sentence[index];
index++;
}
last = ' ';
index = hold;
/* Dont print space after 1st word*/
if(index > 0)
cout<<" ";
}
}
int main()
{
char* sentence = new char[256];
cin.getline(sentence, 256);
reverse(sentence);
delete[] sentence; // Delete the allocated memory
}
Run Code Online (Sandbox Code Playgroud)
尽量让它接近你的逻辑