7-151 统计字符出现次数 (20 分)

本题要求编写程序,统计并输出某给定字符在给定字符串中出现的次数。

输入格式:

输入第一行给出一个以回车结束的字符串(少于80个字符);第二行输入一个字符。

输出格式:

在一行中输出给定字符在给定字符串中出现的次数。

输入样例:

programming is More fun!
m

输出样例:

2

代码一:

#include <stdio.h>
#define M 80
int main (){
	int sum=0;
	char a[M];
	int i;
	for(i=0;i<M;i++){
		scanf("%c",&a[i]);
		if(a[i]=='\n')break;
	}
	char ch;
	scanf("%c",&ch);
	for(i=0;i<M;i++){
		if(a[i]==ch)sum++;
		if(a[i]=='\n')break;
	}
	printf("%d",sum);
}

代码二:

#include<stdio.h>
#include<string.h>
int main(void){
    int i,k,count=0;
    char s[80];
    char a[1];
    gets(s);
    scanf("%c",&a[0]);
    k=strlen(s);
    for(i=0;i<=k;i++){
        if(s[i]==a[0])count++;
    }
    printf("%d",count);
    return 0;
}

代码三:

#include<stdio.h>
int main()
{
    int i=0,t=0;
    char d,a[80],c,count=0;
    d=getchar();
    while(d!='\n'){
       a[i]=d;
       d=getchar();
       i++;
    }
    c=getchar();
    while(t<i){
      if(a[t]==c){
        count++;
      }
      t++;
    }
    printf("%d",count);
    return 0;
}

代码四:

#include<stdio.h>
int main()
{
    char a[80];
    int i,j,b,c;
    char d;
    i=0;
    while((b=getchar())!='\n')
    {
        a[i]=(char)b;
        i++;
    }
    c=0;
    scanf("%c",&d);
    for(j=0;j<i;j++)
    {
        if(a[j]==d)
        {
            c++;
        }
    }
    printf("%d",c);
    return 0;
}

代码五:

#include <stdio.h>
#include <string.h>
int main()
{
    char string[80],character,char_serial;
    int count = 0,i = 0,lenth = 0;
    char_serial = getchar();
    for(i = 0;char_serial != '\n';i++)
    {
    	string[i] = char_serial;
    	lenth += 1;
    	char_serial = getchar();
	}
    scanf("%c",&character);
    for(i = 0;i < lenth;i++)
    {
		if(character == string[i])
            count += 1;
    }
    printf("%d",count);
    return 0;
}
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值