对于这道题,首先要将整个字符串按照字母整个进行翻转,然后再单词内进行翻转,重点在与分割出单词来,设两个标志first和last分别表示单词的开始和结束位置,连续空格的第一个或单一的一个空格前一个位置是前一个单词的结尾,连续空格的最后一个空格的下一个位置是下一个单词的开始。
代码如下:
#include<iostream>
#include<string>
using namespace std;
class WordsReverse
{
public:
WordsReverse(string* _words) : words(_words){}
string* reverseWord();
private:
string* words;
};
string* WordsReverse::reverseWord()
{
string str = "";
string temp;
int size = words->size() - 1;
while(size >= 0)
{
temp = "";
while(size >= 0 && words->at(size) != ' ')
{
temp = words->at(size) + temp;
size--;
}
str += temp;
temp = "";
while(size >= 0 && words->at(size) == ' ')
{
str += ' ';
size--;
}
}
*words = str;
return words;
}
int main()
{
string str = "I am a student.";
WordsReverse *ch = new WordsReverse(&str);
cout<<*(ch->reverseWord())<<endl;
return 0;
}