将字符串student a am i反转为 i am a student

#include <stdio.h>
#include <string.h>

void reserve_string(char *l, char *r)
{
    while(l < r)
    {
        char tmp = *l;
        *l = *r;
        *r = tmp;
        l ++;
        r --;
    }
}
void reserve(char ch[], int len)
{
    int i = 0;
    char *chl = ch;
    char *chr = ch;
    while(ch[i])  
    {
        if(ch[i] == ' ')
        {
            reserve_string(chl, chr - 1);  //先反转每个单词,函数的嵌套调用 tneduts a ma i
            chl = ++chr; //先给chr +1,再把ch的值付给chl

        }
        else
        {
            chr ++;
        }
        i++;
    }
    reserve_string(ch, ch +len-1);  //再整体反转 i am a student

}
int main()

{
    char ch[] = "student a am i";
    reserve(ch , strlen(ch));
    printf("%s\n",ch);
    return 0;
}

你可能感兴趣的:(将字符串student a am i反转为 i am a student)