题目:
编写函数reverse(s),将字符串s中的字符顺序颠倒过来。使用该函数编写一个程序,每次颠倒一个输入行中的字符顺序。
自我解答:
reverse的编程思路是先获取数组中字符的长度,然后进行前后交换,并不对‘\0’进行交换。s[0]和s[len - 1]进行交换,s[1] 和 s[len - 2]进行交换,以此类推
#include <stdio.h>
#define MAXLINE 1000
void reverse(char s[]);
int getline(char s[]);
void reverse(char s[])
{
int len = 0, i;
char c;
while(s[len] != '\0') //get length of the string
len++;
for(i = 0; i < len/2; i++)
{
c = s[i];
s[i] = s[len - i - 1];
s[len - i - 1] = c;
}
}
int getline(char s[])
{
int c;
int len = 0;
while(len < MAXLINE - 1 && (c = getchar()) != EOF && c != '\n')
{
s[len] = c;
len++;
}
if(c == '\n')
{
s[len] = c;
len++;
}
s[len] = '\0';
return len;
}
int main()
{
char line[MAXLINE];
while(getline(line) > 0)
{
reverse(line);
printf("%s", line);
}
return 0;
}
把输入置为上面程序中的main部分,得到输出如下:
)(niam tni
{
;]ENILXAM[enil rahc
)0 > )enil(enilteg(elihw
{
;)enil(esrever
;)enil ,"s%"(ftnirp
}
;0 nruter }
注意:由于每行的结尾是一个换行符,所以反转之后先打印的是换行符。
用gcc编译时,由于stdio.h中已经有了getline()的定义,在编译时会报如下error
test.c:5:5: error: conflicting types for 'getline'
int getline(char s[]);
^
In file included from test.c:1:0:
/usr/include/stdio.h:678:20: note: previous declaration of 'getline' was here
extern _IO_ssize_t getline (char **__restrict __lineptr,
^
test.c:21:5: error: conflicting types for 'getline'
int getline(char s[])
^
In file included from test.c:1:0:
/usr/include/stdio.h:678:20: note: previous declaration of 'getline' was here
extern _IO_ssize_t getline (char **__restrict __lineptr,
参考答案:
#include <stdio.h>
#define MAXLINE 1000
int getline(char line[], int maxline);
void reverse(char s[]);
/* reverse input lines, a line at a time */
int main()
{
char line[MAXLINE]; /* current input line */
while(getline(line, MAXLINE) > 0)
{
reverse(line);
printf("%s", line);
}
}
/* reverse: reverse string s */
void reverse(char s[])
{
int i, j;
char temp;
i = 0;
while(s[i] != '\0') /* find the end of string s */
++i;
--i; /* back off from '\0' */
if(s[i] == '\n')
--i; /* leave newline in place */
j = 0; /* begining of new string */
while(j < i)
{
temp = s[j];
s[j] = s[i]; /* swap the characters */
s[i] = temp;
--i;
j++;
}
}
/* getline: read a line into s, return length */
int getline(char s[], int lim)
{
int c, i ,j;
j = 0;
for(i = 0; (c = getchar()) != EOF && c != '\n'; ++i)
{
if(i < lim - 2)
{
s[j] = c; /* line still in boundaries */
j++;
}
}
if(c == '\n')
{
s[j] = c;
++j;
++i;
}
s[j] = '\0';
return i;
}
reverse函数先要找到字符串s的末尾,然后从'\0'倒退一个位置,这样可以保证颠倒后得到的字符串的第一个字符不会成为一个字符串结束符。如果从'\0'倒退一个位置后遇到的是一个换行符'\n',那就再倒退一个位置,因为换行符也像'\0'一样出现在行的末尾。
变量j先被设置为字符串的第一个字符下标,变量i则被设置为字符串最后一个字符的下标。在交换字符的过程中,程序将对变量j进行递增(即从字符串的第一个字符向字符串的尾部方向移动),对变量i进行递减(即从字符串的最后一个字符向字符头方向移动)。整个过程将一直进行到变量j大于或等于i是停止。
主程序每次读取一个输入行,颠倒之,然后把颠倒后的文本行打印出来。
函数getline()与练习1-16中的同名函数相同(上述程序已贴)
补充:
对于getline的探讨一如前面练习所述。参考答案reverse函数中对于s[],没有查找s中的换行符'\n',所以不会出现1-18练习中的数组越界问题。
对于参考答案reverse中的while循环,参照后面的解答更容易理解。
自我解答中并没有对换行符进行特殊处理,若增加对其处理,可以在while循环之后增加对换行符\n的检测,如下:
if(s[len - 1] == '\n')
len--;