L1-101 别再来这么多猫娘了!(string类关键函数解决)

关键函数详解:

1.string类的find函数返回一个整数,表示查找的子串在字符串中首次出现的位置。如果找到子串,返回值是子串第一个字符在字符串中的索引位置,索引从0开始。如果没有找到子串,则返回string::npos,这是一个特殊的值,表示没有找到匹配项。string::npos是一个非常大的值,通常用作未找到的标记。

2.string类的replace(startPos, from.length(), to)

这里 startPos 是一个整数,表示要开始替换操作的位置。这个位置是之前通过find函数找到的子串"from"在字符串str中的起始索引。

from.length() 计算的是被替换子串"from"的长度。因为replace函数需要知道要替换多少字符。通过传递from.length()作为第二个参数,告诉函数从startPos开始的连续多少个字符需要被替换掉。

to 是要用来替换"from"的新的字符串。

cpp 复制代码
#include<iostream>
#include<cmath>
#include<algorithm>
#define rep(i,a,n) for(int i=a;i<=n;i++)
using namespace std;
signed main()
{
	ios::sync_with_stdio(false);    
	cin.tie(0);
	cout.tie(0);
	int n,k,cnt=0;
    cin>>n;
    string hex="<censored>";
    string tmp="*-*"; //<censored>本身也会成为屏蔽词,先替换成别的
    string str[110];
    string pas;
    cin.ignore();
    rep(i,1,n){
        getline(cin,str[i]);
    }
    cin>>k;
    cin.ignore();
    getline(cin,pas);
    //正确输入整段文本,
    rep(i,1,n){
        while(pas.find(str[i])!=string::npos){
            int last=pas.find(str[i]);
            pas.replace(pas.find(str[i]),str[i].length(),tmp);
            if(last==pas.find(str[i])) break;
            cnt++;
        }
    }
    while(pas.find(tmp)!=string::npos){
        pas.replace(pas.find(tmp),tmp.length(),hex);
    }
    if(cnt<k){
        cout<<pas<<'\n';
    }
    else cout<<cnt<<'\n'<<"He Xie Ni Quan Jia!";
	return 0;
}
注意避开的坑:

1.整数和整行文本输入时需要用cin.ignore()吸收换行符

2.<censored>本身也会成为屏蔽词,需要先替换成别的

3.避免陷入替换的无限循环导致超时

相关推荐
·present·3 小时前
CSAPP(lecture 4_01)
c语言·c++
FPGA小迷弟3 小时前
用 Claude Code 重构遗留系统:从评估到落地的完整实践指南
c++·python·ai·plotly·django·ai编程·claude
程序员-King.3 小时前
【ROS1】Noetic 开发工作流程与常用命令
c++·ubuntu·ros
云深麋鹿3 小时前
C++ | 基于红黑树实现mymap与myset
开发语言·c++
傲世仙尊5 小时前
string增删查改-insert-erase-replace与find加substr组合技
c++
·present·6 小时前
CSAPP(lecture 3)
c++
别动我齐刘海7 小时前
机器人 C++ / 系统联调补强2——异常处理、Protobuf
linux·c++·人工智能·学习·算法·机器学习·机器人
basketball6167 小时前
C++ 中字符串与常见类型的转换总结
开发语言·c++
等我调个Bug7 小时前
C++智能指针通俗讲解
开发语言·c++
kyle~9 小时前
时间同步 --- PTP 与 Scheduled Action Command
c++·数码相机·机器人·传感器