字符个数统计

1、题目描述

编写一个函数,计算字符串中含有的不同字符的个数。字符在ACSII码范围内(0~127)。不在范围内的不作统计。

输入描述:

输入N个字符,字符在ACSII码范围内(0~127)。

输出描述:

输出字符的个数。

输入例子:

abc

输出例子:

3

2、算法

方案一

/*编写一个函数,计算字符串中含有的不同字符的个数。字符在ACSII码范围内(0~127)。不在范围内的不作统计*/
//输入描述:输入N个字符,字符在ACSII码范围内(0~127)
//输出描述:输出字符的个数 
#include<iostream> using namespace std; int main(){ char ch; int arr[128]={0}; int count=0; while(cin>>ch){ if(ch>=0 && ch<=127){ arr[ch]++; } } for(int i=0;i<128;i++){ if(arr[i]>0) count++; } cout<<count<<endl; return 0; }

 注意:这里实际上就是桶排序的思想。

方案二

/*C++
输入字符,ascii值在[0,127]时插入集合set中,输出set中的元素个数。*/
#include<iostream>
#include<set>
using namespace std;
int main()
{
    char c;
    set<char> s;
    while(cin>>c){
        if(c>=0 && c<=127){
            s.insert(c);
        }
    }
    cout << s.size() <<endl;
}

  

方案三

#include<iostream>
#include<string>
#include<map>
using namespace std;
int main()
{
   string s;
   int num=0;
   map<char,int> str;
   while(cin>>s)
   {
       for(int i=0;i<s.length();i++)
       {
           if((s[i]<=127)&&(s[i]>=0))
           {
              str.insert(pair<char,int>(s[i],1));
           }
           else
           {
              continue;
           }
       }
       cout<<str.size()<<endl;
   }
    return 0;  
}

 

 

posted @ 2016-05-23 10:51  程序员姜戈  阅读(286)  评论(0编辑  收藏  举报