如:输入"Somewhere i belong."
输出"Belong.i Somewhere"
请高手展示代码
[此贴子已经被HJin于2007-7-26 0:03:15编辑过]
/*---------------------------------------------------------------------------
File name: ReverseWords.c
Author: HJin (email: fish_sea_bird [at] yahoo [dot] com )
Created on: 7/25/2007 09:05:10
Environment: Windows XP Professional SP2 English +
Visual Studio 2005 v8.0.50727.762
Modification history:
===========================================================================
1. I wrote this function a few years ago. Fully test it before delivering it
to your client.
2. I removed comments to force you study the code instead of copy it.
3. Good luck!
*/
#include <stdio.h>
#include <string.h>
void strsrev(char* p, char* r)
{
char t;
while(p<r)
{
t = *p;
*p++ = *r;
*r-- = t;
}
}
/**
Reverse words in place.
O(n) algorithm.
*/
void wordrev(char* s)
{
char*b =s, *e = s+strlen(s)-1;
if(!s)
return;
strsrev(b, e);
b=e=s;
while(*b)
{
while(*b && *b == ' ')
++b;
e = b;
while(*e && *e != ' ')
++e;
strsrev(b, e-1);
b=e;
}
}
int main()
{
char s[100] = "Somewhere i belong.";
wordrev(s);
*s &= 0xDF;
printf("%s\n", s);
return 0;
}
红字部分看的不是很懂啊,当第一次循环结束后,b和e应该都指向.belong中的l的位置吧。然后执行while(*b && *b == ' ') ++b;语句,b能指向i吗?
还有e刚执行完第一次循环后,不是也指向l吗,如何在第二次调用strsrev(b, e-1);时,指向i呢?