字符串集合算法题汇总(使用C++和python语言)--mid001

14 篇文章 0 订阅
计算字符的个数

在这里插入图片描述

需要注意的是字符不区分大小写还有字符中可能含有空格

#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;
}

除了tolowertoupper方法之外,其实还可以通过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 的异常。

输入一行字符,分别统计出包含英文字母、空格、数字和其它字符的个数。

在这里插入图片描述
难度不大,可以使用isalphaisdigit来判断字母和数字,' '判断空格,剩下的就是其余字符

#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
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值