码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2017-03-06 13:33:38      阅读:180      评论:0      收藏:0      [点我收藏+]

标签:函数   bsp   sdn   无限   names   注意   name   while   ace   

关于接收字符,我用的是输入到‘\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.csdn.net/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;
}

 

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

标签:函数   bsp   sdn   无限   names   注意   name   while   ace   

原文地址:http://www.cnblogs.com/jianrenguo/p/6508956.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!