c++反转字符串
时间: 2025-04-26 09:12:19 浏览: 26
### 实现字符串单词顺序反转
为了实现在 C++ 中按照单词来翻转字符串的功能,可以遵循特定的算法逻辑。该过程涉及先去除输入字符串两端的空白字符,处理中间多余的空格,并最终逆转整个字符串中的单词次序[^1]。
对于给定的例子 `s = "the sky is blue"` ,目标返回的结果应为 `"blue is sky the"` 。此操作不仅限于标准情况下的字符串;即使存在首尾空格或多词间有多个空格的情况也需妥善处理[^2]。
下面是一个具体的解决方案:
```cpp
#include <algorithm>
#include <sstream>
#include <vector>
std::string reverseWords(std::string s) {
std::istringstream iss(s);
std::vector<std::string> words;
// Extract words from the stream and push into vector.
for (std::string word; iss >> word;) {
words.push_back(word);
}
// Reverse the order of elements in the container.
std::reverse(words.begin(), words.end());
// Join all strings together with space separator.
std::ostringstream oss;
if (!words.empty()) {
auto it = words.begin();
oss << *it++;
while (it != words.end()) {
oss << ' ' << *it++;
}
}
return oss.str();
}
```
上述代码首先利用 `istringstream` 将原始字符串分割成单个词语并存储在一个向量中。接着调用 `std::reverse()` 函数颠倒这些词语的位置。最后通过 `ostringstream` 把它们重新组合起来形成新的字符串,在各单词之间加入适当数量的空间分隔符。
阅读全文
相关推荐
















