字符个数统计(C/C++)

来源:互联网 发布:excel数据透视表作用 编辑:程序博客网 时间:2024/06/05 13:23
题目描述
编写一个函数,计算字符串中含有的不同字符的个数。字符在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;}