先把每个单词反转,再反转整个句子
#include <stdio.h>
#include <iostream>
#include <assert.h>
using namespace std;
void reverseWord(char *begin, char *end)
{
assert(begin != NULL && end != NULL);
char c;
while (begin < end)
{
c = *begin;
*begin = *end;
*end = c;
++begin;
--end;
}
return;
}
void reverseSent(char * s)
{
if (s == NULL)
return;
char *begin, *end;
begin = s;
end = s;
bool isInBlank = false;
while (*end != '\0')
{
if ((*(end+1) == ' ' || *(end+1) == '\0') && !isInBlank)
{
reverseWord(begin, end);
isInBlank = true;
}
else if (*(end+1) != ' ' && isInBlank)
{
begin = end+1;
isInBlank = false;
}
++end;
}
if (end - s > 1)
reverseWord(s, end-1);
}
int main(void)
{
char src[256];
gets(src);
cout<<"str is:"<<src<<endl;
reverseSent(src);
cout<<"\nthe dest str:"<<src<<endl;
}
______________________________________________
input:123 4 678
str is:123 4 678
the dest str:678 4 123
_____________________________________________
input: I am a student!
str is:I am a student!
the dest str:student! a am I