跳到正文

个人记录

字符串

xiaowu1120约 4 分钟
原文
文章信息与版本

文章信息

收录
2025年12月12日
更新
2026年5月1日
篇幅
约 4 分钟

版本

  1. v1当前

字符串之间就是按照字典序来比较(>、三三字典序比较规则:逐位比较 当前谁大 它的字典序大 erase():字符串删除函数s.erase(idx,len):从字符串s的下标idx开始删除长度为len的字符串补充:没有len的话 把idx及后面都删除s=“abcdefg”;s.erase(3,2);=>s=“abcfg”; find():字符串查找函数s.find(ss,idx):从字符串s的下标idx开始查找ss第一次出现的下标找到了返回第一次出现的下标 没有找到返回string::npos补充:没有idx的话 查找从0开始ss第一次出现的下标 substr():字符串截取子串(连续的一段)函数s.substr(idx,len):从字符串s的下标idx开始截取长度为len的字符串

B3663 [语言月赛202209] Luogu Academic

错误代码:

C++
#include<bits/stdc++.h>
using namespace std;
int main(){
	string s,t="luogu";
	cin>>s;
	int sum=0,ans=0;
	int j=0;
	for(int i=1;i<=s.size();i++){
        if(s[i]!=t[j])j=0;
		if(s[i]==t[j]){
			sum++;
		}
		if(sum==5){
			ans++;
		}
		j++;
	}
	cout<<ans;
	return 0;
}

正确代码: 正确思路:用查找函数,找不到返回

C++
#include<bits/stdc++.h>
using namespace std;
int main(){
	string s,ss="luogu";
	cin>>s;
    int ans=0;
    int x=0;
    while(s.find(ss,x)!=string::npos){
        ans++;
        x=s.find(ss,x)+1;
    }
    cout<<ans;
	return 0;
}

B4048 [语言月赛 202410] 断章取义

正确思路:要用双重循环,起点在s.find(ss,x),长度是3

C++
#include<bits/stdc++.h>
using namespace std;
int main(){
	int t;
    cin>>t;
    string s,ss="not";
    cin>>s;
    int ans=0;
    while(s.find(ss)!=string::npos){
      int x=0;
        ans++;
        while(s.find(ss,x)!=string::npos){
            int y=s.find(ss,x);
            s.erase(y,3);
            x=y;
        }
     }
    cout<<s<<endl<<ans;
	return 0;
}

B3769 [语言月赛202305] 制糊串

错误思路:不会substr,用两个for复值,下面l1,l2,是要减1;

C++
#include<bits/stdc++.h>
using namespace std;
int main(){
	string s,t;
	cin>>s>>t;
	int q;
	cin>>q;
	int l1,r1,l2,r2;
	while(q--){
	int sum=0,ans=0;
    string ss,tt;
	cin>>l1>>r1>>l2>>r2;
	ss=s.substr(l1,r1-l1+1);
    tt=t.substr(l2,r2-l2+1);
	if(ss>tt)cout<<"erfusuer\n";
	else if(ss<tt)cout<<"yifusuyi\n";
	else cout<<"ovo\n";
	}
	return 0;
}

正确代码:

C++
#include<bits/stdc++.h>
using namespace std;
int main(){
	string s,t;
	cin>>s>>t;
	int q;
	cin>>q;
	int l1,r1,l2,r2;
	while(q--){
	int sum=0,ans=0;
    string ss,tt;
	cin>>l1>>r1>>l2>>r2;
	ss=s.substr(l1-1,r1-l1+1);
    tt=t.substr(l2-1,r2-l2+1);
	if(ss>tt)cout<<"erfusuer\n";
	else if(ss<tt)cout<<"yifusuyi\n";
	else cout<<"ovo\n";
	}
	return 0;
}
原文