题意:
给定一个字符串S,反转其中存在的单词顺序
例如:输入S = “ This is a good day”;
输入 “day good a is This”
另外,若字符串开头和结尾有空格要将其删除,单词间的空格仅保留一个
题目思路:
先整个反转字符串,然后对于每个单词分别进行反转,在期间处理多余的空格,代码若有不足之处欢迎大家指正。
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
void reverseWords(string &s)
{
char *pStr = NULL;
char *pRes = NULL;
int nFlag = 0;
int nLoc = 0;
int nhead = 0;
int ntail = 0;
string::size_type sizeStr = s.size();
pStr = (char*)malloc((sizeStr+1) * sizeof(char));
pRes = (char*)malloc((sizeStr+1) * sizeof(char));
reverse(s.begin(),s.end());
for (string::size_type i = 0; i< sizeStr; i++)
{
pStr[i] = s[i];
}
for (string::size_type i = 0; i< sizeStr; i++)
{
if (pStr[i] != ' ' && nFlag == 0)
{
nFlag = 1;
nhead = i;
}
if (pStr[i] == ' ' && nFlag == 1)
{
ntail = i;
for (int k = i-1; k>=nhead; k--)
{
pRes[nLoc++] = pStr[k];
}
pRes[nLoc++] = ' ';
nFlag = 0;
}
}
if (nFlag == 1)
{
for (int k = s.size()-1; k>=nhead; k--)
{
pRes[nLoc++] = pStr[k];
}
pRes[nLoc] = '\0';
}
else
pRes[nLoc-1] = '\0';
//cout<<pRes<<endl;
s = pRes;
free(pStr);
free(pRes);
}
int main()
{
string s(" 1");
reverseWords(s);
cout<<s<<endl;
system("pause");
}