翻转句子中单词顺序

来源:互联网 发布:mac打开terminal快捷键 编辑:程序博客网 时间:2024/05/21 21:41

题目:

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

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

解决方法:

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

#include <stdio.h>#include <string.h>//the string to be dealing withchar 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 0
原创粉丝点击