字元個數統計(C/C++)
阿新 • • 發佈:2018-12-24
題目描述
編寫一個函式,計算字串中含有的不同字元的個數。字元在ACSII碼範圍內(0~127)。不在範圍內的不作統計。 輸入描述:
輸入N個字元,字元在ACSII碼範圍內。 輸出描述:
輸出範圍在(0~127)字元的個數。 輸入例子:
abc 輸出例子:
3 方法一,利用set容器的去重特性:
編寫一個函式,計算字串中含有的不同字元的個數。字元在ACSII碼範圍內(0~127)。不在範圍內的不作統計。 輸入描述:
輸入N個字元,字元在ACSII碼範圍內。 輸出描述:
輸出範圍在(0~127)字元的個數。 輸入例子:
abc 輸出例子:
3 方法一,利用set容器的去重特性:
方法二,利用陣列進行統計#include<iostream> #include<set> using namespace std; int main() { char c; set<char> myset; while (cin >> c) { if (c >= 0 && c <= 127) myset.insert(c); } cout << myset.size() << endl; system("pause"); return 0; }
#include<iostream> using namespace std; int main() { char c; int a[128] = { 0 }; int count = 0; while (cin >> c) { if (c >= 0 && c <= 127) a[c]++; } for (int i = 0; i < 128; i++) { if (a[i]>0) count++; } cout << count << endl; //system("pause"); return 0; }