機試之字符串——統計字符
鏈接:
算法筆記刷題筆記
1、題目
題目描述
統計一個給定字符串中指定的字符出現的次數。
輸入描述:
測試輸入包含若干測試用例,每個測試用例包含2行,第1行爲一個長度不超過5的字符串,第2行爲一個長度不超過80的字符串。注意這裏的字符串包含空格,即空格也可能是要求被統計的字符之一。當讀到'#'時輸入結束,相應的結果不要輸出。
輸出描述:
對每個測試用例,統計第1行中字符串的每個字符在第2行字符串中出現的次數,按如下格式輸出:
c0 n0
c1 n1
c2 n2
...
其中ci是第1行中第i個字符,ni是ci出現的次數。
示例1:
輸入:
I
THIS IS A TEST
i ng
this is a long test string
#
輸出:
I 2
i 3
5
n 2
g 2
2、代碼
//機試之字符串——統計字符
//字符串的統計
#include <iostream>
#include <cstdio>
#include <cstring>
#include <string>
#include <algorithm>
using namespace std;
int main(){
string str1,str2;
int cnt[150];
while(getline(cin,str1)){
memset(cnt,0,sizeof(cnt));//計數器初始化爲0
if(str1 == "#"){//統計結束標誌
break;
}
getline(cin,str2);
for(int i = 0 ;i < str2.size(); ++i){
cnt[str2[i]]++;//此處str2[i]爲字符?可以自動轉換爲下標數字嗎
}
for(int i = 0 ;i < str1.size(); ++i){
cout<<str1[i]<<" "<<cnt[str1[i]]<<endl;
}
}
return 0;
}