Reverse the ordering of words in a string

后端 未结 30 4337
青春惊慌失措
青春惊慌失措 2020-11-22 10:23

I have this string s1 = \"My name is X Y Z\" and I want to reverse the order of the words so that s1 = \"Z Y X is name My\".

I can do it u

30条回答
  •  被撕碎了的回忆
    2020-11-22 11:13

    We can insert the string in a stack and when we extract the words, they will be in reverse order.

    void ReverseWords(char Arr[])
    {
        std::stack s;
        char *str;
        int length = strlen(Arr);
        str = new char[length+1];
        std::string ReversedArr;
        str = strtok(Arr," ");
        while(str!= NULL)
        {
            s.push(str);
            str = strtok(NULL," ");
        }
        while(!s.empty())
        {
            ReversedArr = s.top();
            cout << " " << ReversedArr;
            s.pop();
        }
    }
    

提交回复
热议问题