C++字符串 单词倒置

#include <iostream>
#include <vector>
#include <string>
#include <algorithm>

using namespace std;

void out(string n)
{
     cout << n << ' ';
}

int main()
{

     char a[]="what are you doing";//变成"tahw era uoy gniod"
     vector <string> iv;
     const char * split=" ";
     char * p;
     p = strtok (a,split);
     string s;
     while(p!=NULL)
     {
          s = p;
          reverse(s.begin(),s.end());
          iv.push_back(s);
          p = strtok(NULL,split);
     }
     s.~string();
     for_each(iv.begin(),iv.end(),out);
     cout<<endl;
     system("pause");
     return 0;
}

### C++ 中实现字符串翻转的方法 #### 使用 `std::reverse` 函数 为了简化开发过程并利用已有的高效实现,可以直接使用 `<algorithm>` 头文件中提供的 `std::reverse` 函数来完成字符串的翻转操作。下面是一段简单的代码示例: ```cpp #include <iostream> #include <string> #include <algorithm> int main() { std::string str = "hello"; std::reverse(str.begin(), str.end()); std::cout << str << std::endl; } ``` 这段代码展示了如何通过调用 `std::reverse` 来快速有效地逆转给定的字符串变量 `str` 的内容[^1]。 #### 手动交换字符位置的方式 如果希望更深入理解底层机制,则可以通过遍历字符串的一半长度,并逐个交换对应索引处的字符来进行翻转。这里给出了一种不依赖于 STL 库的手工实现方式: ```cpp void reverseString(std::string &s) { int n = s.length(); for (int i = 0; i < n / 2; ++i){ char temp = s[i]; s[i] = s[n - i - 1]; s[n - i - 1] = temp; } } // 测试该函数 int main(){ std::string testStr = "example"; reverseString(testStr); std::cout<<testStr<<'\n'; } ``` 此方法同样实现了字符串的完全倒置功能,适用于那些想要学习更多关于指针运算以及数组访问细节的学习者。 #### 特殊情况下的字符串翻转——单词顺序保持不变而整体逆序排列 对于某些特定应用场景下可能遇到的要求保留原有单词内部字母次序的同时仅改变整个句子结构的情况,可以采用如下策略解决: ```cpp #include <sstream> #include <vector> using namespace std; string ReverseWords(string input) { stringstream ss(input); vector<string> words; string word, result=""; while(ss >> word){ // 将输入按空格分割成多个子串存入向量words中 words.push_back(word); } for(auto it=words.rbegin();it!=words.rend();++it){ if(it != --words.rend()){ result += *it + ' '; }else{ result += *it; } } return result; } // 测试上述函数 int main(){ cout<<ReverseWords("the sky is blue")<<"\n"; // 输出:"blue is sky the" } ``` 这种方法特别适合处理像题目描述那样的实例,在去除首尾多余空白之后再执行相应的转换逻辑[^4]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值