将student a am i翻转成i am a student。
方法:
(1)先将所有字符串进行翻转,即变成“i ma a tneduts”,
(2)当遇到空格时,则把空格前那段字符进行翻转,接着往下判断。
#include <stdio.h>
#include <string.h>
#include <assert.h>
char * fanzhuan(char *str)
{
assert(str);
char *l = str;
char *r = str;
while(*r != ‘\0‘)
{
r++;
}
while(l < r-1)
{
char tmp = *l;
*l = *(r-1);
*(r-1) = tmp;
l++;
r--;
}
l = str;
r = str;
while(*r != ‘\0‘)
{
while(*r != 32 && *r != ‘\0‘)
{
r++;
}
char *p = r;
while(l < r-1)
{
char tmp = *l;
*l = *(r-1);
*(r-1) = tmp;
l++;
r--;
}
if(*p == ‘\0‘)
{
return str;
}
l = p+1;
r = p+1;
}
return str;
}
int main ()
{
char a[] = "student a am i";
char *ret = fanzhuan(a);
printf("%s\n",ret);
return 0;
}
更好的代码个人还没想出,有待提高。
时间: 2024-10-07 16:38:50