单词的逆序 C语言实现

发布于:2023-01-22 ⋅ 阅读:(2) ⋅ 点赞:(0) ⋅ 评论:(0)

C语言实现单词的逆序
例:

how are you!  -->  woh era !uoy
I love kust!  -->  I evol !tsuk

运行结果:
在这里插入图片描述
实现代码:

#include <stdio.h>

void word_reverse(char *start)
{
    char *end = start;
    char *i, *j, tmp;
    while(*end != '\0')
    {
        /* end 定位到 空格 */
        while(*end != ' ')
        {
            if(*end == '\0')
            {
                break;
            }
            end++;
        }

        /* 逐个单词逆序 */
        i = start;
        j = end - 1;
        while(i < j)
        {
            tmp = *i;
            *i = *j;
            *j = tmp;
            i++;
            j--;
        }
        
        /* 更新头尾标记 */
        start = end + 1;
        end++;
    }

    /* 逆序最后一个单词 */
    i = start;
    j = end;
    while(i < j)
    {
        tmp = *i;
        *i = *j;
        *j = tmp;
    }

}

int main()
{
	//默认句子
    char sentence[] = "I love kust!";
    printf("Before: ");
    puts(sentence);

    word_reverse(sentence);

    printf("After : ");
    puts(sentence);
    
    return 0;
}