翻轉單詞順序列(C++)
阿新 • • 發佈:2018-12-30
題目:
給定一個輸入字串,其中各個單詞之間由空格分開,每個單詞的字元是順序的,但是單詞之間的順序是逆序的。
實現一個翻轉單詞序列的演算法。
如:
輸入:student. a am I
輸出:I am a student.
思路:
從左往右遍歷字串,逐個拼接每個單詞即可。
貼程式碼:
#include <iostream> #include <string> using namespace std; string ReverseSentence(string str) { string res = "", tmp = ""; for(unsigned int i = 0; i < str.size(); ++i) { // 遇到空格 if(str[i] == ' ') { res = " " + tmp + res; tmp = ""; } else { tmp += str[i]; } } // 最後一個字元 if(tmp.size()) res = tmp + res; return res; } int main(void) { string str = "student. a am I"; cout<<ReverseSentence(str)<<endl; return 0; }