1. 題目描述
寫出一個程序,接受一個由字母和數字組成的字符串,和一個字符,然後輸出輸入字符串中含有該字符的個數。不區分大小寫。
-
輸入描述:
第一行輸入一個有字母和數字以及空格組成的字符串,第二行輸入一個字符。 -
輸出描述:
輸出輸入字符串中含有該字符的個數。
輸入:
ABCDEF
A
輸出
1
2. 思路
這道題直觀的思路是可以利用STL的count函數,但是忽略大小寫直接套用就不行了。一種直觀的思路就是將輸入string和ch都變成小寫字母或者大寫,然後在count就可以了。
3. 代碼
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
char ToLower(char& ch) {
char result = ch;
if (isupper(ch)) {
result = tolower(ch);
}
return result;
}
int main() {
string str;
char ch;
while (cin >> str >> ch) {
ch = ToLower(ch);
transform(str.begin(), str.end(), str.begin(), ::tolower);
cout << count(str.begin(), str.end(), ch);
}
}
4. 參考文獻
但是如果不能修改原來的字符串,那麼就需要換別的思路了。這裏主要是熟悉transform函數,count函數,isupper, toupper等函數的。