对字符串中所有单词进行倒排。用C++实现
时间: 2023-12-03 21:47:04 浏览: 34
以下是一个简单的C++代码实现,使用了STL的vector和algorithm库函数:
```c++
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main()
{
string s;
getline(cin, s); // 输入字符串
vector<string> words; // 定义一个 vector 存储单词
string word;
for (char c : s) { // 遍历字符串中的每个字符
if (isalpha(c)) { // 如果字符是字母,则将其加入当前单词
word += c;
} else { // 否则将当前单词加入 vector,并清空当前单词
if (!word.empty()) {
words.push_back(word);
word.clear();
}
}
}
if (!word.empty()) { // 处理最后一个单词
words.push_back(word);
}
reverse(words.begin(), words.end()); // 将 vector 中的单词倒排
// 输出结果
for (int i = 0; i < words.size(); i++) {
cout << words[i];
if (i != words.size() - 1) {
cout << " ";
}
}
cout << endl;
return 0;
}
```
该代码首先读入一个字符串,然后遍历字符串中的每个字符,以空格为分隔符将字符串分割成单词,并将这些单词存储在 vector 中。最后,使用 STL 的 reverse 函数将 vector 中的单词倒排,并输出结果。