#include "stdafx.h"
#include "iostream"
#include
#include
#include
using namespace std;
void reverse_word(char pBegin,char *pEnd);
char reverse_word_in_sentence(char *pData);
int _tmain(int argc, _TCHAR* sargv[])
{ char str[]="I love you!";
char *st=reverse_word_in_sentence(str);
cout<<str<<endl;
system("pause");
}
void reverse_word(char *pBegin,char *pEnd)
{
if(pBegin == nullptr || pEnd == nullptr)
return;
//int n=pEnd-pBegin;
//int i,j;
//for(i=0,j=n;i<j;i++,j--)
while(pBegin<pEnd)
{
char temp = *pBegin;
*pBegin= *pEnd;
*pEnd=temp;
pBegin++;
pEnd--;
}
}
char* reverse_word_in_sentence(char *pData)
{
if(pData == nullptr)
return nullptr;
char *pBegin = pData;
char *pEnd= pData;
while(*pEnd != '\0')
{
pEnd++;
}
pEnd--;
//翻转整个句子
reverse_word(pBegin,pEnd);
//翻转句子中的每个单词
pBegin = pEnd = pData;
while(*pBegin!='\0')
{
if(*pBegin == ' ')
{
pBegin++;
pEnd++;
continue;
}
//翻转单词
else if(*pEnd == ' ' || *pEnd == '\0')
{
reverse_word(pBegin,--pEnd);
//begin指针设置为下一个单词位置
pBegin=pEnd++;
}
else
{
pEnd++;
}
}
}