题目1021:统计字符------------------------主要注意输入的方法,如何让一长串的字符都接收到字符串中
Posted 贱人郭
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了题目1021:统计字符------------------------主要注意输入的方法,如何让一长串的字符都接收到字符串中相关的知识,希望对你有一定的参考价值。
关于接收字符,我用的是输入到‘\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:统计字符------------------------主要注意输入的方法,如何让一长串的字符都接收到字符串中的主要内容,如果未能解决你的问题,请参考以下文章
题目1021:统计字符------------------------主要注意输入的方法,如何让一长串的字符都接收到字符串中