字符数组应用:统计单词个数&&求三个字符串中最大者

45 阅读1分钟

题目1:输入一行字符,统计其中有多少个单词,单词之间用空格分隔开。

思路:

①将一行字符存在字符数组中,从第一个字符开始循环。

②当单个字符为空格时,表明没有字符,word=0;当单个字符不是空格时,表明有字符,判断该字符前(word)是否有字符,若无(word=0),则word=1,num++。若有字符,则继续循环。(word类似一个信号量的作用)

#include<stdio.h>
#include<string.h>
int main(){ 
	char str[100];
	int i,num=0,word=0;
	char c;
	gets(str);
	for(i=0; (c=str[i])!='\0'; i++){
		if(c==' ') word=0;//没有词 
		else //当前不是空格,即有字符时
			if(word==0){//前边是空格 
				word=1; //表示前边是单词 
				num++; //存放单词个数 
			}
	}
	printf("单词的个数:%d",num); 
	return 0;
} 

题目2:有三个字符串,要求找出其中“最大”者,并输出最大者。

思路:用字符串比较函数strcmp来比较字符串的大小。

#include<stdio.h>
#include<string.h>
int main(){
	char s1[100],s2[100],s3[100],a[100];
	scanf("%s%s%s",s1,s2,s3);
	if(strcmp(s1,s2)>0){ //s1大 
		if(strcmp(s1,s3)>0) printf("%s",s1);
		else printf("%s",s3);
	}else{ //s2大 
		if(strcmp(s2,s3)>0) printf("%s",s2);
		else printf("%s",s3);
	}
	return 0;
} 

注意:在用字符串函数时,记得加头文件string.h 。