计算字符的个数
需要注意的是字符不区分大小写还有字符中可能含有空格
#include<iostream>
#include<string>
using namespace std;
int main()
{
string s1,s2;
while(getline(cin,s1)&&getline(cin,s2)){
char c = tolower(s2[0]);
int count = 0;
for(int i = 0;i <s1.size();++i){
if(tolower(s1[i]) == c)
++count;
}
cout << count << endl;
}
return 0;
}
除了tolower
和toupper
方法之外,其实还可以通过ASCII码进行比较(考虑到)
if(s1[i]==c||s1[i]+32==ch||s1[i]-32==ch)
然后是python
a=input().lower()
b=input().lower()
print(a.count(b))
字符个数统计
这道题可以使用集合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>
using namespace std;
int main(){
char ch;
int arr[128]={0};
int count=0;
while(cin>>ch){
if (ch=='\0')
break;
if(ch>=0 && ch<=127){
arr[ch]++;
}
}
for(int i=0;i<128;i++){
if(arr[i]>0)
count++;
}
cout<<count<<endl;
return 0;
}
python
看了一个网友写的,看来大家都挺着急的hhh
print len(set([i for i in input() if ord(i) in range(128)]))
笔记:
ord
以一个字符(长度为1的字符串)作为参数,返回对应的ASCII
数值,或者Unicode
数值,如果所给的 Unicode
字符超出了你的 Python
定义范围,则会引发一个 TypeError
的异常。
输入一行字符,分别统计出包含英文字母、空格、数字和其它字符的个数。
难度不大,可以使用isalpha
和isdigit
来判断字母和数字,' '
判断空格,剩下的就是其余字符
#include<iostream>
#include<string>
using namespace std;
int main()
{
string s;
while(getline(cin,s))
{
int countA = 0, countB = 0, countC = 0,countD = 0;
for(auto i:s)
if(isalpha(i))
countA++;
else if (isdigit(i))
countC++;
else if(i==' ')
countB++;
else
countD++;
cout<<countA<<endl<<countB<<endl<<countC<<endl<<countD<<endl;
}
return 0;
}
知识点:
C++11引入for循环的新特性auto
,再也不用羡慕别人家for range循环了
遍历字符串✔
遍历数组✔
遍历容器✔
遍历map✔ 返回的是pair变量
python
的解法,isnumeric
判断是否是数字,isalpha
判断是否是字母
while True:
try:
a=input()
CountA,CountB,CountC,CountD=0,0,0,0
for i in a:
if i==" ":
CountB+=1
elif i.isnumeric():
CountC+=1
elif i.isalpha():
CountA+=1
else:
CountD+=1
print(CountA)
print(CountB)
print(CountC)
print(CountD)
except:
break