题目1021:统计字符------------------------主要注意输入的方法,如何让一长串的字符都接收到字符串中...

本文介绍了两种实现字符匹配计数的方法:一种使用 C 语言,通过无限循环接收两行字符并统计第一个字符串中的字符在第二个字符串中出现的次数;另一种采用 C++ 的方式,利用标准字符串库函数进行类似的字符匹配计数。

关于接收字符,我用的是输入到‘\0’就结束的策略;

#include<stdio.h> 
int main()
{ 
    while(true)//这里用的while(true)来表示无限循环
    {    
    int i=0,j=0;
        int count[5]={0,0,0,0,0};
        char str1[5],str2[80]; 
       char ch;
        while(scanf("%c",&ch)!=EOF)
        {
            if (ch=='#') return 0;
            else if (ch=='\n') break;
            else  str1[i++]=ch; 
        }
        str1[i]='\0';
        char cr;
         while(scanf("%c",&cr)!=EOF) 
         {
             if(cr=='\n') break;
               else str2[j++]=cr;
         }
         str2[j]='\0';
     for(i=0;str1[i]!='\0';i++)
        for(j=0;str2[j]!='\0';j++) 
          if (str2[j]==str1[i]) count[i]++;
     
    for (i=0;i<5;i++) 
        if (count[i]!=0)
          printf("%c %d\n",str1[i],count[i]);
    }  
     return 0;
} 

其实,我最中意的是这种代码:转载自http://blog.youkuaiyun.com/mnmlist/article/details/25185563

 #include<iostream>
#include<string>
using namespace std;
int main()
{
    while(true)//同样的无限循环的策略
    {
        int count[1000]={0};
        string str1,str2;
        getline(cin,str1);//标准的c++式的输入一行,当然空格也接收
        if(str1=="#")
            break;
        getline(cin,str2);
        int k=str1.length();
        for(int i=0;i<k;i++)
        {
            int j=0;
            while(true)
            {
                j=str2.find(str1[i],j);//用的是关于string 的标准容器的find函数
                if(j!=-1){count[i]++;j++;}
                else
                    break;
            }
            cout<<str1[i]<<' '<<count[i]<<endl;
        }
    }
    return 0;
}

 

转载于:https://www.cnblogs.com/jianrenguo/p/6508956.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值