c语言刷题:洛谷P1308 [NOIP2011 普及组] 统计单词数

题目链接:[NOIP2011 普及组] 统计单词数 - 洛谷


1.首先需要大写转小写(如果你不嫌麻烦可以小写转大写)。


void to_lower(char* p)
{
	while (*p != '\0')
	{
		if (*p >= 'A' && *p <= 'Z')
			*p += 32;
		p++;
	}
}

2.然后就是统计:(没错就是这么直接)

下面是全部代码:


#define _CRT_SECURE_NO_WARNINGS 1
#include
#include
#include
int count;//记录单词数
int flag;//标记是不是第一次出现该单词
int pos;//第一次出现的位置
int num;//当前位置
void to_lower(char* p)//大写转小写
{
	while (*p != '\0')
	{
		if (*p >= 'A' && *p <= 'Z')
			*p += 32;
		p++;
	}
}
int main()
{
	int num = 0;
	char arr[11] = "\0";
	gets(arr);
	to_lower(arr);
	int len = strlen(arr);
	char array[1000000] = "\0";
	gets(array);//要注意这里读取字符串用的是两个的gets,因为上一行输入的带有回车,用scanf第二行的gets就读不到东西,因为回车还在缓冲区
	char* p = array;
	to_lower(array);
	while (*p)
	{
		if (isspace(*p))//空格跳过
		{
			num++;
			p++;
			continue;
		}
		if (!strncmp(arr, p, len) && isspace(p[len]))//比对的单词一样而且单词末尾是空格(如果是字母单词就不是同一个单词)
		{
			if (!flag)//第一次找到就保存地址
			{
				pos = num;
				flag = 1;
			}
			count++;
			p += len + 1;
			continue;
		}
		while (islower(*p))//如果比对不正确,那么这一个单词就不是,就要跳过
		{
			p++;
			num++;
		}
	}
	if (count)
	{
		printf("%d %d", count, pos);
	}
	else printf("-1");
}

如果你要问我为什么写篇博客这么直接,那我是不会告诉你我困了,熬夜写的博客就是这么直接,点点赞咯,一个赞我多敲一道题(助力我实现这个不知死活的梦想)。

你可能感兴趣的:(c语言)