計算字符個數
題目描述 寫出一個程序,接受一個有字母和數字以及空格組成的字符串,和一個字符,然后輸出輸入字符串中含有該字符的個數。不區分大小寫。
輸入描述: 輸入一個有字母和數字以及空格組成的字符串,和一個字符。
輸出描述: 輸出輸入字符串中含有該字符的個數。
輸入例子: 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;}新聞熱點
疑難解答