c语言——按单词反转字符串

来源:互联网 发布:淘宝大刀 编辑:程序博客网 时间:2024/06/05 13:28

例如:Hi what your name
result:name your what Hi

#include <stdio.h>#include <windows.h>char *reverse_word(const char *str){    int len = strlen(str);    char *restr = new char(len + 1);    strcpy(restr, str);    int i, j;    for (i = 0, j = len - 1; i < j; i++, j--)    {        char temp = restr[i];        restr[i] = restr[j];        restr[j] = temp;    }    int k = 0;    while (k < len)    {        i = j = k;        while (restr[j]!= ' '&&restr[j]!='\0')                            {            j++;        }        k = j + 1;        for (; i < j; i++, j--)        {            char temp = restr[i];            restr[i] = restr[j-1];            restr[j-1] = temp;        }    }    return restr;}int main(){    char *str = "Hi what is your name";    char *result = NULL;    result=reverse_word(str);    printf("%s\n", result);    return 0;}
原创粉丝点击