在一个句子里单词逆转秩序 [英] Reversing order of words in a sentence

查看:118
本文介绍了在一个句子里单词逆转秩序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

#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.

样intput和输出应该是这样的:

Sample intput and output should be like this:

Howdy Mr. Mcfly? 

Mcfly? Mr. Howdy

从哪里获得:

Howdy Mr. Mcfly?
 Mcfly?

有在互联网很多类似的问题,但我想要的是找到错误在我自己的code。

There are many similar questions around the internet but what i want is to find error in my own code.

推荐答案

至于其他的答案建议你应该使用的std ::字符串这可以节省很多麻烦的。
但只是为了备忘,

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆