题目
输入一篇可能未经排版的文章,挑选出其中的单词【单词中不包含“(”等特殊符号】,然后按字典序输出。
样例
- 输入
When most kids go to school and study the knowledge, few special kids have made their history. A small boy from America wins the international contest by defeating adult competitors. He becomes the youngest winner. He has the gift and so many parents want to have such a kid. Though we are not that smart, we still can study hard to realize our dreams. - 输出
a
adult
america
and
are
becomes
boy
by
can
competitors
contest
defeating
dreams
few
rom
gift
go
hard
has
have
he
history
international
kid
kids
knowledge
made
many
most
not
our
p
rents
realize
school
small
smart
so
special
still
study
such
that
the
their
though
to
want
we
when
winner
wins
youngest
分析
从输入的txt文件中读取字符串,分离得到每个单词,一律变为小写,再按字典序即ASCII码值对每个单词进行排序,在这里将输出也写入文件。
代码
#include <srdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#define SIZE 20 // 最长单词长度
#define NUM 150 // 最大单词数量
int compar(const void*, const void*);
int main(int argc, char *argv[])
{
char ch, temp[SIZE] = "\0", *str[NUM];
FILE* fp; // 读取文件指针
FILE* wp; // 写入文件指针
fp = fopen("filein.txt", "r");
wp = fopen("fileout.txt", "w");
if(fp == NULL || wp == NULL)
exit(EXIT_FAILURE);
int n = 0, num = 0;
while((ch = getc(fp)) != EOF)
{
/* 是字母则加入单词字符串数组,
不是则在字符串数组后加上'\0'并赋给指针数组*/
if(isalpha(ch))
temp[n ++] = tolower(ch);
else if(n)
{
temp[n] = '\0';
n = 0;
str[num] = (char*)calloc(strlen(temp), sizeof(char));
strcpy(str[num ++], temp);
memset(temp, '\0', sizeof(temp));
}
}
qsort(str, num, sizeof(char*), compar);
int i;
for(i = 0;i < num;++ i)
{
fputs(str[i], wp);
putc('\n', wp);
}
fclose(fp);
fclose(wp);
for(i = 0;i < num;++ i)
free(str[i]);
return 0;
}
int compar(const void* a, const void* b)
{
return strcmp(*((char**)a), *((char**)b));
}