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

本文介绍了一种方法,用于统计文章中特定单词的出现次数及其位置,通过字符处理和字符串比较实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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


// test.cpp : Defines the entry point for the console application.
//

#include<stdio.h>
#include<string.h>
#define MAX_size 10000
int 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]);
	}
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值