Reversing order of words in a sentence

后端 未结 8 1257
伪装坚强ぢ
伪装坚强ぢ 2020-12-04 02:11
#include 
#include 
using namespace std;
void reverse(char* sentence)
{
    int index = strlen(sentence) - 1;
    char last = \'\\0\';         


        
相关标签:
8条回答
  • 2020-12-04 02:49
    #include <sstream>
    #include <iostream>
    #include <list>
    
    int main() {
        char sentence[256];
        std::cin.getline(sentence, 256);
    
        std::istringstream f(sentence );
    
        std::string s;  
        std::list<std::string> strings;
    
        while (f >> s) 
        {
            strings.push_front(s);
        }
    }
    

    at this moment strings contains the words in reverse order

    0 讨论(0)
  • 2020-12-04 02:51

    You can use std::string std::vector and std::reverse to make things easier:

    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);
    }
    

    Now you have everything separated into words. You may now want to remove question marks or other punctuation, since the logic will be easier to implement while the words are still in the correct order. For reversing, do this:

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

    You'll need to include several headers:

    #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
    

    You can see this code in action with this demo on ideone.com

    0 讨论(0)
提交回复
热议问题