c++实现:将一句话中的单词倒置,标点符号不倒换。
时间: 2024-02-17 10:05:02 浏览: 65
以下是C++的实现代码:
```c++
#include <iostream>
#include <vector>
#include <sstream>
using namespace std;
string reverse_words(string sentence) {
// 将句子按照空格分割成单词列表
vector<string> words;
stringstream ss(sentence);
string word;
while (ss >> word) {
words.push_back(word);
}
// 对单词列表进行倒置
reverse(words.begin(), words.end());
// 将倒置后的单词列表重新组成一个句子
string reversed_sentence = "";
for (int i = 0; i < words.size(); i++) {
reversed_sentence += words[i];
if (i != words.size() - 1) {
reversed_sentence += " ";
}
}
return reversed_sentence;
}
int main() {
string sentence = "Hello world, I am a chatbot.";
string reversed_sentence = reverse_words(sentence);
cout << reversed_sentence << endl;
return 0;
}
```
使用方法:
将上述代码保存为`reverse_words.cpp`文件,然后在终端中执行以下命令进行编译和运行:
```
g++ reverse_words.cpp -o reverse_words
./reverse_words
```
输出结果:
```
chatbot. a am I world, Hello
```
阅读全文