题目如下
给定一个字符串str,将字符串中的单词位置进行反转,输出反转结果。
“student. a am I”。
“I am a student.”
解题方法
逐个单词进行判断,如果不是空格的话,用tmp暂时保存,如果是空格,那么res = " "+tmp+res 方式反转
#include<iostream>
#include<string>
using namespace std;
string ReverseSentence(string str)
{
string res = "", tmp = "";//初始化为空字符串
for (unsigned int i = 0; i < str.size(); ++i)
{
if (str[i] == ' ')
res = " " + tmp + res, tmp = "";
else
tmp += str[i];
}
if (tmp.size())
res = tmp + res;
return res;
}
int main()
{
string s1 = "student. a am I";
cout << ReverseSentence(s1) << endl;
return 0;
}