题目描述
编写一个函数,计算字符串中含有的不同字符的个数。字符在ACSII码范围内(0~127)。不在范围内的不作统计。
输入描述:
输入N个字符,字符在ACSII码范围内。
输出描述:
输出范围在(0~127)字符的个数。
示例1
输入
abc
输出
3
C++:
- 方法一
正常计数,如若在前面的字符串中碰到一样的字符,count - 1
#include <iostream>
#include <string>
using namespace std;
int main()
{
string s;
while (getline(cin, s))
{
int count = 0;
for (int i = 0; i < s.size(); i++)
{
if (int(s[i]) >= 0 && int(s[i]) <= 127)
{
count++;
for (int j = 0; j < i; j++)
{
if (s[i] - s[j] == 0)
{
count -= 1;
break;
}
}
}
}
cout << count << endl;
}
return 0;
}
- 方法二
str.find()函数找不到会返回string::npos,直接ASCII码0-127之间遍历寻找,找到计数+1
#include <iostream>
#include <string>
using namespace std;
int main()
{
string s;
while (getline(cin, s))
{
int count = 0;
for(int i = 0; i < 128; i++)
{
if (s.find(i) != string::npos)
{
count++;
}
}
cout << count << endl;
}
return 0;
}
python:
a = set(input())
count = 0
for i in a:
if 0 <= ord(i) <= 127:
count += 1
print(count)