计算字符个数
题目描述 写出一个程序,接受一个有字母和数字以及空格组成的字符串,和一个字符,然后输出输入字符串中含有该字符的个数。不区分大小写。
输入描述: 输入一个有字母和数字以及空格组成的字符串,和一个字符。
输出描述: 输出输入字符串中含有该字符的个数。
输入例子: ABCDEF A
方法一:#include <iostream>#include <string>using namespace std;int count(string str,char ch){ int sum = 0,i=0; while(str[i]!='/0') { if(str[i]==ch||str[i]==ch+32||str[i]==ch-32) sum++; ++i; } return sum;}int main(){ string str; int s; char ch; getline(cin,str); cin>>ch; s = count(str,ch); cout<<s<<endl; return 0;}方法二:#include <iostream>#include <map>using namespace std;int main(){map<char,int>Words;char ch;while ((ch=getchar())){ if(ch=='/n') break; else words[ch]++;} cin>>ch;if((ch>='a')&&(ch<='z')){ cout<<words[ch]+words[ch-32]<<endl;}else if ((ch>='A')&&(ch<='Z')){ cout<<words[ch]+words[ch+32]<<endl;}else cout<<words[ch]<<endl; return 0;}新闻热点
疑难解答