C语言编程练习(一)

问题描述:.给出一个英语句子,希望你把句子里的单词顺序都翻转过来    

输入样例:I love you    输出样例:you love I 

 1 /*************************************************************************
 2     > File Name: main.c
 3     > Author: 
 4     > Mail: 
 5     > Created Time: 2018年12月29日 星期六 09时17分27秒
 6  ************************************************************************/
 7 
 8 #include <stdio.h>
 9 #include <string.h>
10 
11 void Rolate(char *str, int len);/*翻转句子,但单词不变,如I love you->you love I*/
12 void RotateStence(char *str, int from ,int to);/*翻转句子,如I love you->uoy evol I*/
13 void RotateWord(char *str, int len);/*翻转单词,避开空格*/
14 
15 int main()
16 {
17     int len;
18     char *find;
19     char str[300];
20     printf("Please input a string\n");
21     fgets(str,300,stdin);
22     find = strchr(str, '\n');          //查找换行符
23     if(find)                            //如果find不为空指针
24     *find = '\0';                    //就把一个空字符放在这里
25     len = strlen(str);
26     Rolate(str, len);
27     printf("%s\n", str);
28     return 0;
29 }
30 
31 void RotateStence(char *str, int from, int to)
32 {
33     char tmp;
34     while(from < to)
35     {
36         tmp = str[from];
37         str[from++] = str[to];
38         str[to--] = tmp;
39     }
40 }
41 
42 void RotateWord(char *str, int len)
43 {
44     int i=0, j=0;
45     for(int k=0; k<len; k++)
46     {
47         if(str[k] != ' ')
48         {
49             j++;
50         }
51         else
52         {
53             RotateStence(str, i, j-1);
54             i = ++j;
55         }
56     }
57 }
58 
59 void Rolate(char *str, int len)
60 {
61     RotateStence(str, 0, len-1);
62     RotateWord(str, len);
63 }

猜你喜欢

转载自www.cnblogs.com/lhsy/p/10195117.html
今日推荐