C程序设计语言 (第二版) 练习1-19
练习 1-19 编写函数 reverse(s),将字符串s 中的字符顺序颠倒过来。使用该函数编写一个程序,每次颠倒一个输入行中的字符顺序。
注意:代码在win32控制台运行,在不同的IDE环境下,有部分可能需要变更。
IDE工具:Visual Studio 2010
代码块:
#include <stdio.h>
#include <stdlib.h>
#define MAXLINE 1000
int getline(char s[], int lim){
int c, i;
for(i = 0; i < lim - 1 && (c = getchar()) != EOF && c != '\n'; ++i){
s[i] = c;
}
s[i] = '\0';
return i;
}
void reverse(char s[]){
int i, len;
for(i = 0; s[i] != '\0'; i++);
len = i;
char temp;
for(int i = 0, j = len - 1; i < len / 2; i++, j--){
temp = s[i];
s[i] = s[j];
s[j] = temp;
}
}
int main(){
int len;
char line[MAXLINE];
while((len = getline(line, MAXLINE)) > 0){
reverse(line);
printf("%s\n", line);
}
system("pause");
return 0;
}