作者:小 琛
欢迎转载,请标明出处
题目:
将一句话进行倒置,标点不倒置。例如:I like bejing. -> bejing. like I
分析:
这道题目和简单得倒置有所不同,并不是单纯得所有内容颠倒,而是要保持每个单词不变,仅仅将单词的次序倒置。
解题思路:将问题简单化,要完成该要求,可以先将所有的内容倒置,接着将每个单词再倒置,即可完成要求
#include <iostream>
#include <string>
//将一句话进行倒置,标点不倒置。例如:I like bejing. -> bejing. like I
//逆置函数,参数为两个指针,可将某区域内的内容逆置
void resever(std::string::iterator s1, std::string::iterator s2)
{
while (s1 < s2)
{
std::swap(*s1, *s2);
s1++;
s2--;
}
}
//主函数
void resever_str()
{
std::string str;
std::getline(std::cin, str);//从键盘获取一串字符,满足空格
resever(str.begin(), str.end() - 1);//先总体逆置
std::string::iterator head = str.begin();
std::string::iterator tail = str.begin()+1;
while (tail !=str.end())
{
while (*tail == ' ')//当tail碰到空格,表示遇到了一个单词,逆置该单词
{
resever(head, tail - 1);
head = tail+1;
tail++;
continue;
}
tail++;
}
resever(head, tail - 1);//增加最后一个单词是没有逆置成功的,要额外加一次
for (auto v : str)//范围for打印
{
std::cout << v;
}
}