这里程序实现分两步,第一步是先将整个字符串反转过来,第二步是把里面的每个单词再次反转。
student a am i
经第一步操作后
变成:i ma a tneduts
经第二步操作后
变成:i am a student
int my_lenth(const char *s) //求出字符串的总长度
{
assert(s); //断言,不能传空指针
int lenth = 0;
while (*s++ != '\0')
{
lenth++;
}
return lenth;
}
void reversal_word(char *start, char *end) //把一个字符串从头到尾反转
{
assert(start && end);
while (start < end)
{
char tem = *start; //头和尾交换
*start = *end;
*end = tem;
start++;
end--;
}
}
void Reversal(char *s)
{
assert(s);
int len = my_lenth(s);
char *start = s;
char *end = s + len - 1;
reversal_word(start, end); //第一步先把整个字符串反转
while (*s != '\0')
{
char *tip = s;
while ((*s != ' ') && (*s != '\0'))
{
s++;
}
reversal_word(tip, s-1); //第二步把每个单词再次反转
if (*s != '\0')
{
s++;
}
}
}
int main()
{
char s[] = "tian is name my";
Reversal(s);
printf("%s\n", s);
system("pause");
return 0;
}