主要要求:给定一个字符串,逐个翻转字符串中的每个单词。
示例:
输入: "the sky is blue",
输出: "blue is sky the".
说明:
无空格字符构成一个单词。
输入字符串可以在前面或者后面包含多余的空格,但是反转后的字符不能包括。
如果两个单词间有多余的空格,将反转后单词间的空格减少到只含一个。
源代码:
#include<iostream>
#include<string>
#include<vector>
#include<algorithm>
#include <sstream>
using namespace std;
void reverseWords(string &s)
{
vector<string> result,reverse_result;
string tab_blank = " ";
string sub_string = "";
char tab =' ';
int k = 0;
for (int i = 0; i < s.size(); i++)
{
if (s[i]!=tab)
{
sub_string = sub_string + s[i];
if (i == s.size() - 1)
{
result.push_back(sub_string);
}
}
else
{
if (sub_string.empty())
{
continue;
}
else
{
result.push_back(sub_string);
sub_string = "";
}
}
}
s = "";//把s给清空
for (int m = result.size() - 1; m >= 0; m--)
{
if (m != 0)
{
s = s + result[m];
s = s + tab_blank;
}
else
{
s = s + result[m];
}
}
}
int main()
{
string str1 = " qwe b bb 4 333";
reverseWords(str1);
cout << str1 << endl;
system("pause");
return 0;
}
输出结果:
333 4 bb b qwe