颠倒句子中的单词顺序 [英] Reversing order of words in a sentence
本文介绍了颠倒句子中的单词顺序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
#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);
}
我想颠倒一个句子中单词的顺序,你可以看到我上面的尝试.
I want to reverse the orders of words in a sentence and you can see my attempt above.
样本输入和输出应该是这样的:
Sample intput and output should be like this:
Howdy Mr. Mcfly?
Mcfly? Mr. Howdy
我在哪里:
Howdy Mr. Mcfly?
Mcfly?
互联网上有很多类似的问题,但我想要的是在我自己的代码中找到错误.
There are many similar questions around the internet but what i want is to find error in my own code.
推荐答案
正如其他答案所建议的那样,您应该使用 std::string
可以省去很多麻烦.但只是为了说明,
As the other answers suggest you should use std::string
which can save lot of hassles.
But just for the note,
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
}
尽量让它接近你的逻辑
这篇关于颠倒句子中的单词顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文