将语句单词反转

题目:将语句的单词反转, I am chinese 输出 chinese am I,不能开辟非常量存储空间

算法:先将每个单词反转,再整体反转一次。题很简单,但这个思路一般人不好往这个方向想。

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

inline void swap(char* p1, char* p2)    //交换
{
        char c = *p1;
        *p1 = *p2;
        *p2 = c;
}

void turn(char* str, int len)                   //翻转
{
        int i;
        for(i = 0; i < len / 2; i++)
                swap(str + i, str + len - 1 - i);
}

void turn_words(char* str)                              //  语句单词翻转
{
        char* p = str;
        char* beg = p;
        while(*p != '\0')
        {
                if(*p == ' ')
                {
                        turn(beg, p - beg);                     //翻转每个单词
                        beg = ++p;
                }
                else
                        ++p;
        }
        turn(beg, p - beg);                                     //最后一个单词
        turn(str, strlen(str));                         //整个字符串翻转一次
}

int main()
{
        char* s = (char*)malloc(1024);
        while(scanf("%[^\n]\n", s) == 1)
        {
                turn_words(s);
                printf("%s\n", s);
        }
        free(s);
        return 0;
}
echo "When nine is divided by four the quotient is two with a remainder of one" | ./binm
one of remainder a with two is quotient the four by divided is nine When

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值