字符串题目

P1308统计单词数

题目

#include<bits/stdc++.h>
using namespace std;
#include <stdio.h> 
#include <string.h>
#define maxn 90
void strlower(char *a){
	for(int i=0;a[i];i++){
		if(isupper(a[i]))a[i]=tolower(a[i]);
	}
}
int main(){
	char a[1000001],b[11],*q,*p;//当前搜索到的指针,最后一次搜索到的指针 
	gets(b);
	gets(a);
	bool flag=false;
	int ans=0,ans1=-1;//个数,首个出现的位置
	int len=strlen(b);
	strlower(a);//转换大小写 
	strlower(b);
	p=a;
	for(;q=strstr(p,b);) {
		if(q!=NULL&&(q==a||*(q-1)==' ')&&(*(q+len)=='\0'||*(q+len)==' ')){
			ans++;
			if(flag==false){
				ans1=q-a;//指针-数组首地址=指针下标 
				flag=true;
			}
		}
		p=q+len; 
	}
	if(flag==true)
	cout<<ans<<' '<<ans1;
	else cout<<ans1; 	
}
  1. 大小写字母转换函数,判断 isupper(),转小写 tolower();
  2. 查找字符串b是否存在于字符串a中,p为指针,指向a,q=strstr(p,b),q为出现的首地址
  3. 循环查询是否存在,改变首地址位置,p=q+len
  4. 在文章中查找词组,确保位置*(q-1)是空格或 *q是首地址,单词长度后是空格或结尾
  5. 输出字符在数组中的位置,ans1=q-a,当前指针-数组首地址=下标位置

用string类型

int main(){
    //定义两个字符串
    string a;
    string b;
    //用string库,调用getline, 直接读入一整行
    getline(cin,a);
    getline(cin,b);
    //转换大小写,可以都转换为大写,或者小写
    for (int i=0;i<a.length();++i){
        a[i]=tolower(a[i]);
    }
    for (int i=0;i<b.length();++i){
        b[i]=tolower(b[i]);
    }
    //因为连起来的不算,所以要在前后加几个空格,一定要是同样多的,同量减同量,等于同量
    a=' '+a+' ';
    b=' '+b+' ';
    //先看看会不会找不到,用a.find()和string::npos
    if (b.find(a)==string::npos){
        cout<<-1<<endl;
    }
    //如果找得到
    else {
        int alpha=b.find(a);
        int beta=b.find(a),s=0;//计数器初始化为0
        while (beta!=string::npos){
            ++s;//计数器
            beta=b.find(a,beta+1);
        }
        cout<<s<<" "<<alpha<<endl;//输出第一个和总共有几个
    }
    //函数返回值为0,结束整个程序
    return 0;
}

  1. 查找字符串a是否包含子串b,用 strA.find(strB) != string::npos

  2. beta=b.find(a,beta+1);从上一次出现的位置开始(a,beta+1),beta+1是新位置

  3. a=’ ‘+a+’ ‘; b=’ ‘+b+’ '; 统一格式,保证查找时是标准单词

  4. a.length()是字符串长度

  5. getline(cin,a),输出字符串

P1588垂直柱状图

题目

#include<bits/stdc++.h>
using namespace std;
int main()
{
	char a[200];
	int maxn=0,ff[26]={0},n;
	for(int i=0;i<4;i++){
		gets(a);
		n=strlen(a);
		for(int j=0;j<n;j++){
			if(a[j]>='A'&&a[j]<='Z') ff[a[j]-'A']++;//isalpha判断字母
		}
		//cout<<a;
	}
	//for(int i=0;i<26;i++)cout<<ff[i]<<' ';
	
	for(int i=0;i<26;i++)maxn=max(maxn,ff[i]);//循环找最大值
	for(int i=maxn;i>0;i--){
		for(int j=0;j<26;j++){
			if(ff[j]>=i)cout<<"*";
			else cout<<" ";
			if(j!=25)cout<<" ";
		}
		cout<<'\n';
	}
	for(int i=0;i<26;i++)printf("%c ",i+'A');//%串,顺序输出字母
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值