金山2014秋招笔试题——统计单词在一篇文章中出现的次数和位置

来源:互联网 发布:淘宝联盟如何领优惠券 编辑:程序博客网 时间:2024/06/05 02:32

题目:统计单词在一篇文章中出现的次数和位置


// test.cpp : Defines the entry point for the console application.//#include<stdio.h>#include<string.h>#define MAX_size 10000int flag=1,times=0;char hke(char c){return (((c<='z')&&(c>='a'))||((c<='Z')&&(c>='A')));}char _loHKE(char c){if((c>='A')&&(c<='Z'))return (c+32);return c;}void Index(char str[],char word[],int position[]){int i,len_str,len_word,pos_str=0,pos_word=0,k=0,word_number=0; /* word_number represent? number of word in article */len_word=strlen(word);len_str=strlen(str);for(i=0;i<len_str;){while(!hke(str[i]))i++;word_number++; /*the number of words add one */for(pos_str=i,pos_word=0;pos_str<len_str && pos_word<len_word;pos_str++,pos_word++){if(_loHKE(str[pos_str])!=_loHKE(word[pos_word]))break;}if(pos_word==len_word && (str[pos_str]=='\0'|| !hke(str[pos_str]) )) /* represent finding the equal word */{position[k++]=word_number;times++; /*the times of equality add one*/flag=0;}else{while(hke(str[pos_str]) && pos_str<len_str)pos_str++;}i=pos_str;}}void  main(){FILE *fp;char str[MAX_size],word[20];char c;int i=0;int position[100];fp=fopen("f:\\t.txt","r");if(fp==NULL){printf("\nThe file can not open!");// exit(0);return;}c=fgetc(fp);while(c!=EOF){str[i++]=c;c=fgetc(fp);}//puts(str);printf("Please enter the word you want to see about: \n");gets(word);Index(str,word,position);if(flag)printf("There is no such word you entered in the article. \n");else{printf("In the article the word you entered appears %d times in all\n",times);printf("The position of word of appearance are: \n");for(i=0;i<times;i++)printf("The%2dth word.\n",position[i]);}}


0 0
原创粉丝点击