下面是一个经典例子
writing a program that will sort a set of text lines into alphabetic order, a
stripped-down version of the UNIX program sort.
自己做的答案
除了main函数,还有函数 pzcmp, pzprint, pzsort 还有 getline
我觉得pzcmp和getline非常重要,需要特别掌握。
其中,getline是逐行输入,原型为 int getline(char *s, int lim), 把每一行包括末尾的回车一起读到字符数组s中,返回实际读入的字节数。EOF不读。lim为一次最多能够读入的字节数。
int getline(char *s, int lim){ int nr = 0; for(; lim > 0 && (*s = getchar()) != EOF && *s != '\n'; lim--, s++) nr++; if(*s == '\n') nr++; return nr; }
|
pzcmp是比较从指定位置为起点到以回车符为结尾的两个字符串。
int pzcmp(char **lp, int i, int j){ char *s1 = lp[i], *s2 = lp[j]; while(*s1 == *s2){ if(*s1 == '\n') return 0; s1++; s2++; } if(*s1 == '\n') return 0 - *s2; if(*s2 == '\n') return *s1; return *s1 - *s2; }
|
整个程序的源代码:
#include<stdio.h> int pzcmp(char **lp, int i, int j){ char *s1 = lp[i], *s2 = lp[j]; while(*s1 == *s2){ if(*s1 == '\n') return 0; s1++; s2++; } if(*s1 == '\n') return 0 - *s2; if(*s2 == '\n') return *s1; return *s1 - *s2; } void pzprint(const char *s){ while(putchar(*s), *s++ != '\n') ; } void pzsort(char *s){ char *lp[100]; int i, n = 1; lp[0] = s; while(*s){ if(*s == '\n' && *(s + 1) != '\0') lp[n ++] = s + 1; s ++; } int j, k; char *t; for(i = 0; i < n; i ++){ k = i; for(j = i; j < n; j ++){ if(pzcmp(lp, k, j) > 0) k = j; } t = lp[k]; lp[k] = lp[i]; lp[i] = t; } for(i = 0; i < n; i ++){ pzprint(lp[i]); } } //read a line ended by EOF or '\n', or by approching the limit.
//but it doesn't add a '\0' to the end.
int getline(char *s, int lim){ int nr = 0; for(; lim > 0 && (*s = getchar()) != EOF && *s != '\n'; lim--, s++) nr++; if(*s == '\n') nr++; return nr; } int main(){ char s[1000], *p = s; /* int n; scanf("%d", &n); getchar(); while(n > 0){ p += getline(p, s + 1000 - p); n --; } */ int nr; while((nr = getline(p, s + 1000 - p))) p += nr; *p = '\0'; pzsort(s); }
|
阅读(581) | 评论(0) | 转发(0) |