注意:最后一个单词后面不能再输出空格
// 判断是“构成单词的字符” 还是“非构成单词的字符” bool isWordCharacter(char c) #include <iostream> #include <string> #include <vector> #include <algorithm> using namespace std; // 判断字符是否是构成单词的字符 bool isWordCharacter(char c); int main() { string sentence; while(getline(cin, sentence)) { // 分离每一个单词,将每一个单词装进vector中 vector<string> words; string word = ""; for(char c : sentence) { if(isWordCharacter(c)) word += c; else if(!isWordCharacter(c) && word != "") { words.push_back(word); word = ""; } } if(word != "") words.push_back(word); // 对单词进行倒排 reverse(words.begin(), words.end()); // 输出结果(注意:最后一个单词后面不能再有空格 !!!) int index = 0; while(index < words.size() - 1) { cout << words[index] << " "; ++index; } cout << words[index] << endl; } return 0; } // 判断字符是否是构成单词的字符 bool isWordCharacter(char c) { return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z'); }