思路就是先整体翻转这个句子变为:
won uoy ssim I
任何以单词为单位进行翻转
now you miss I;
以上就是思想,具体代码如下:
// ReverseSentence2.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include <iostream>
using namespace std;
void Reverse(char* pb , char* pe) //将某一段字符串翻转过来
{
char *pl = pb , *pr = pe;
while(pl!=pr&&pl&&pr)
{
char temp = *pl; //不能写成char * temp = pl;否则交换字符的操作失败
*pl = *pr;
*pr = temp;
if(pl+1==pr)break;
pl++;
pr--;
}
}
char* ReverseSentence(char* pData)
{
if(!pData)
return NULL;
char* pb=pData;
char* pe=pData;
while(pe && *pe!='\0')
pe++;
pe--;
Reverse(pb,pe);//翻转整个单词
pb = pe =pData;//指针重新指到句子的头
while (pe && *pe!='\0')
{
while (*pe!='\0'&&pe && *pe!=' ')
pe++;
pe--;
Reverse(pb,pe);
++pe;
while(*pe!='\0'&&*pe==' ')
pe++;
pb=pe;
}
return pData;
}
int _tmain(int argc, _TCHAR* argv[])
{
/*char str[]="abcd";
int len = sizeof(str)/sizeof(char);
Reverse(str,str+len-2);
cout<<str<<endl;*/
char str[]="I miss you now";
cout<<ReverseSentence(str)<<endl;
system("pause");
return 0;
}
程序输出: