北航研究生复试2015上机第3题

题目

输入一篇可能未经排版的文章,挑选出其中的单词【单词中不包含“(”等特殊符号】,然后按字典序输出。

样例

  1. 输入
    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.
  2. 输出
    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));
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值