首页 > 其他 > 详细

练习1-19 编写函数reverse(s),将字符串s中的字符顺序颠倒过来。使用该函数编写一个程序,每次颠倒一个输入行中的字符顺序。

时间:2020-04-25 17:50:20      阅读:107      评论:0      收藏:0      [点我收藏+]
 1 #include<stdio.h>
 2 
 3 #define MAXLINE 1000
 4 
 5 int get_Line(char s[],int lim);
 6 void reversestring(char s[]);
 7 
 8 main()
 9 {
10     char line[MAXLINE];   //当前行
11     int len;            //当前行长度
12 
13     while((len = get_Line(line,MAXLINE)) > 0)
14     {
15         reversestring(line);
16         printf("%s\n",line);
17     }
18     return 0;
19 }
20 
21 //获取输入行
22 int get_Line(char s[],int lim)
23 {
24     int c,i,j;
25 
26     j = 0;
27     for(i = 0;(c = getchar()) != EOF && c != \n;++i)
28         if(i < lim - 2)
29         {
30             s[i] = c;
31             ++j;            
32         }
33     if(c == \n)
34     {
35         s[j] = c;
36         ++i;
37         ++j;
38     }
39     s[j] = \0;
40     return i;
41 }
42 
43 //翻转字符串
44 void reversestring(char s[])
45 {
46     int i,j;
47     char temp;
48 
49     i = 0;
50     while(s[i] != \0)  /* find the end of string s */
51         ++i;
52         --i;                /* back off from ‘\0‘  */
53     if(s[i] == \n)
54         --i;            /* leave newline in place  */
55     j = 0;
56     while(j < i)
57     {
58         temp = s[j];
59         s[j] = s[i];    //swap the characters
60         s[i] = temp;
61         --i;
62         ++j;
63     } 
64 }

 

练习1-19 编写函数reverse(s),将字符串s中的字符顺序颠倒过来。使用该函数编写一个程序,每次颠倒一个输入行中的字符顺序。

原文:https://www.cnblogs.com/liuhaiqing/p/12774051.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!