《编程思维与实践》1043.统计单词个数

《编程思维与实践》1043.统计单词个数

题目

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-pUOBHsKc-1683195294191)(C:\Users\Administrator\AppData\Roaming\Typora\typora-user-images\image-20230504180356041.png)]

思路

有余数每行读取,所以需要gets读取后分割字符串,用一个变量存单词再判断其是否为有效单词即可.

需要注意的地方:

由于非有效字符可能出现大小写,所以统一将字符转化为小写字符后判断即可.

代码

#include<stdio.h>
#include<string.h>
#include<ctype.h>

int main()
{
    
    
	int T;
	scanf("%d\n",&T);  //注意读取回车
	for(int i=0;i<T;i++)
	{
    
    
		char s[101];  //长度不超过
		gets(s);
		int j=0;   //遍历s的指标
		int count=0; //单词数
		while(j<strlen(s))
		{
    
    
			while(isspace(s[j]))  //跳过空格
			{
    
    
				j++;
			}
			char temp[101];  //存单词
			int n=0;
			while(j<strlen(s)&&!isspace(s[j]))
			{
    
    
				temp[n++]=(s[j]>='A'&&s[j]<='Z')?s[j]+32:s[j];   //全变为小写字母
				j++;
			}
			temp[n]='\0';
			if(!(strcmp("the",temp)==0||strcmp("a",temp)==0||strcmp("an",temp)==0||strcmp("of",temp)==0||strcmp("for",temp)==0||strcmp("and",temp)==0))   //除去不记个数的情况
			{
    
    
				count++;
			}
		}
		printf("case #%d:\n",i);
		printf("%d\n",count);
	}	
	return 0;
}

猜你喜欢

转载自blog.csdn.net/boxueyuki/article/details/130492560