Sword refers to offer 151. Flip the words in the string [medium]-istringstream

answer:

1.2. Through this question, I learned about istringstream. The istringstream object can bind a line of string, and then separate the line with a space as a separator.

(1) istringstream word (s) first construct a string input stream

  (2) while (word >> w) reads a string from the input stream

class Solution {
public:
    string reverseWords(string s) {
        istringstream word(s);
        string w;
        string res;
        while(word>>w)  res=' '+w+res;
        return res.empty()?"":string(res.begin()+1,res.end());
    }
};

2. It is also using istringstream, you can save each string in the vector, and finally connect

class Solution {
public:
    string reverseWords(string s) {
        istringstream word(s);
        vector<string> vec;
        string w;
        string res;
        while(word>>w)  vec.push_back(w);
        for(int i=vec.size()-1;i>=0;i--)    res+=vec[i]+' ';
        return res.empty()?"":string(res.begin(),res.end()-1);
    }
};

 

Published 65 original articles · Like1 · Visits 495

Guess you like

Origin blog.csdn.net/qq_41041762/article/details/105431668