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.避免陷入替换的无限循环导致超时

相关推荐
Word码1 小时前
[C++语法] 继承 (用法详解)
java·jvm·c++
lxl13071 小时前
C++算法(1)双指针
开发语言·c++
淀粉肠kk1 小时前
C++11列表初始化:{}的革命性进化
c++
zhooyu2 小时前
C++和OpenGL手搓3D游戏编程(20160207进展和效果)
开发语言·c++·游戏·3d·opengl
HAPPY酷2 小时前
C++ 和 Python 的“容器”对决:从万金油到核武器
开发语言·c++·python
茉莉玫瑰花茶3 小时前
C++ 17 详细特性解析(5)
开发语言·c++·算法
cpp_25013 小时前
P10570 [JRKSJ R8] 网球
数据结构·c++·算法·题解
cpp_25013 小时前
P8377 [PFOI Round1] 暴龙的火锅
数据结构·c++·算法·题解·洛谷
程序员老舅3 小时前
C++高并发精髓:无锁队列深度解析
linux·c++·内存管理·c/c++·原子操作·无锁队列
划破黑暗的第一缕曙光3 小时前
[C++]:2.类和对象(上)
c++·类和对象