字符个数统计
描述
编写一个函数,计算字符串中含有的不同字符的个数。字符在 ASCII 码范围内( 0~127 ,包括 0 和 127 ),换行表示结束符,不算在字符里。不在范围内的不作统计。多个相同的字符只计算一次
例如,对于字符串 abaca 而言,有 a、b、c 三种不同的字符,因此输出 3 。
数据范围: 1≤n≤500
输入描述:
输入一行没有空格的字符串。
输出描述:
输出 输入字符串 中范围在(0~127,包括0和127)字符的种数。
前提:关于ASCII码与字符串之间的转换
/*字符出与ASCII码之间的转换*/
char a = 'a';
int n = int(a);
cout << n << endl;
int m = n;
printf("%c", m);
cout<< endl;
结果
输出
97
a
利用C++作答
#include <iostream>
#include <string.h>
using namespace std;
int main(){
//输入字符串
char ch[500];
scanf("%s",&ch);//这里若是用for循环输入到字符串数组中会出现其他问题。
int len=strlen(ch);//获得数组的长度
int flag[128]={0};//标记ASCII码
for(int j=0;j<len;j++){
if(ch[j]>=0 && ch[j]<=127)//这里字符可以直接转换成整数与之比较而不需要函数
//cout<<int(ch[j])<<" ";
flag[ch[j]]+=1;
}
//种类计数
int count=0;
for(int k=0;k<127;k++){
if(flag[k]!=0)
count++;
}
cout<<count;
return 0;
}
输入
abc
输出
3
利用C语言
#include <stdio.h>
int main()
{
int cnt[128]={0};//用来统计个数。
char str[200];//存储字符串。
int i;
int count=0;
gets(str);//输入字符串。
for(i = 0; str[i]!='\0'; ++i)//遍历字符串。
cnt[str[i]]++;//统计个数。
for(i=0;i<128; i ++)//遍历统计到的值。
if(cnt[i]!=0)//如果出现过则打印值,及个数。
// printf("%c:%d\n", i, cnt[i]);//输出结果。
count++;
printf("%d",count);
return 0;
}
输入
abc
输出
3