题目:
本题链接:倒置字符串
将一句话的单词进行倒置,标点不倒置。比如 I like beijing. 经过函数后变为:beijing. like I
输入描述:
输出描述:
示例1:
解题思路:
- 先将整个字符串逆置过来:
.gnijieb ekil I
- 遍历字符串,找出每个单词,对单词逆置:
beijing. like I
。这里通过算法库中的reverse
逆置,所以这里使用迭代器遍历string
图解:
代码:
#include<iostream>
#include<algorithm>
#include<string>
using namespace std;
int main()
{
string str;
getline(cin, str);//getline读一行
//逆置整个字符串
reverse(str.begin(), str.end());
auto start = str.begin();
//找空格,逆置每个单词
while(start != str.end())
{
auto end = start;
//找空格
while(end != str.end() && *end != ' ')
end++;
//找到空格或者走到str.end(), 逆置单词
reverse(start, end);
if(end == str.end())
{
start = end;
}
else
{
start = end + 1;
}
}
cout << str;
return 0;
}