翻转句子中单词顺序

题目:

输入一个英文句子,番句子中单词的顺序,但单词内字符的顺序不变。句子中单词以空格符隔开。为简单起见,标点符号和普通字母一样处理。

例如输入“I am a student.”,则输出“student. a am I”。

解决方法:

处理方法是首先将整个句子翻转,然后再将其中的每个单词翻转。

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

//the string to be dealing with
char str[100];

void swap(char *a,char *b)
{
    char temp;
    temp = *b;
    *b = *a;
    *a = temp;
}

void swap_str(int start,int end)
{
    int low,high;
    low = start;
    high = end;
    while(low < high)
    {
        swap(&str[low],&str[high]);
        low++;
        high--;
    }
}

void reverse_word()
{
    int i,len;
    int s = 0,e = 0;
    len = strlen(str);
    //reverse all the sentence
    swap_str(0,len-1);

    //reverse all the word
    for(i=0;i<len;i++)
    {
        e = i;
        //str[e] is the apace,swap is [s,e-1]
        if(str[e] == ' ')
        {
            swap_str(s,e-1);
            s = e + 1;
        }
    }
}

int main()
{
    strcpy(str,"I am a student");
    reverse_word();
    printf("%s\n",str);
    return 0;
}


  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值