循环+数组+字符串函数经典例题

从键盘输入一段文章,统计单词出现的次数,
这个题涉及循环,数组,字符串处理函数知识,哪一方面薄弱都解决不了问题,即使都理解,不会用也不行,会用但是在循环中各个量的变化情况不了解也不行,需要着三方面知识综合运用

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define HANG_SIZE 100
#define TEXT_SIZE 10000
#define X 500
#define Y 10
int main()
{
int count = 0;
char words[X][Y];
char nword[X] = { 0 };
char hang[HANG_SIZE];
char text[TEXT_SIZE] = { “\0” };
char deli[] = " ,.()!"";
charphang = NULL;
char
ptr = NULL;
//输入一行,并连接到text中,用fgtes()函数
while (true)
{
phang=fgets(hang, sizeof(HANG_SIZE), stdin);
if (hang[0] == ‘\n’)
break;
strcat_s(text, sizeof(text), phang);
}
//输出打印好的text
printf("%s\n", text);
//定义一个strtok函数用到的指针,并第一次单元化,得到第一个单词
ptr = strtok(text, deli);
//将次单词复制到words数组的第一个行元素中,以便循环中进行查找
strcpy_s(words[0], sizeof(words[0]), ptr);
int newword = 1;
++nword[count++];
//查找单词并录入words,并且nword相应元素+1
while (true)
{
ptr = strtok(NULL, deli);
if (!ptr)
break;

	for (int j = 0; j < count; ++j)
	{
		if (strcmp(ptr, words[j]) == 0)
		{
			++nword[j]; newword = 0;
		}
	}
	if (newword)
	{
		strcpy_s(words[count], sizeof(words[count]), ptr);
		++nword[count++];
	}
	else
		newword = 1;
	if (count > X)
	{
		printf("words数组不够用\n"); return 1;
	}
}
for (int k = 0; k < count; ++k)
{
	if (strnlen_s(words[k], sizeof(words[k])) != 0)
		printf("%-5s%2d", words[k],nword[k]);
	if ((k + 1) % 4 == 0)printf("\n");
}
system("pause");
return 0;

}

发布了21 篇原创文章 · 获赞 0 · 访问量 364

猜你喜欢

转载自blog.csdn.net/gaoxingzhe/article/details/104498145