分析:先翻转整个句子,然后再翻转每个单词,每个单词都被翻转两次,所以单词中字母顺序没有变。
另外需要注意两点,第一:翻转完句子后一定要重新设置pBegin=pEnd=pData;如果忘记了这个,这输出和输入时一样的,完全没有翻转;
第二:空字符的表示不是'',而是中间有个空格' ',否则会出现
--------------------Configuration: test2 - Win32 Debug--------------------
Compiling...
myfile.cpp
C:\Microsoft Visual C++\projects\MyProjects\test2\myfile.cpp(38) : error C2137: empty character constant
执行 cl.exe 时出错.
myfile.obj - 1 error(s), 0 warning(s)
#include <iostream>
using namespace std;
void Reverse(char *pBegin,char *pEnd)
{
if(pBegin==NULL||pEnd==NULL)
return;
while(pBegin<pEnd)
{
char temp=*pEnd;
*pEnd=*pBegin;
*pBegin=temp;
pBegin++,pEnd--;
}
}
//reverse the whole sentence
char* ReverseSentence(char *pData)
{
if(pData==NULL)
return NULL;
char *pBegin=pData;
char *pEnd=pData;
while(*pEnd!='\0')
pEnd++;
pEnd--;
//reverse the word
Reverse(pBegin,pEnd);
pBegin=pEnd=pData;
while(*pBegin!='\0')
{
if(*pBegin == ' ')
{
pBegin++;
pEnd++;
continue;
}
else if(*pEnd == ' ' || *pEnd == '\0')
{Reverse(pBegin,--pEnd);
pBegin=++pEnd;
}
else
{
pEnd++;
}
}
return pData;
}
void main()
{
char str[]="I am a student.";
char* result=ReverseSentence(str);
cout<<result<<endl;
}