Binary String Matching STL秒解-不要太简单

本文介绍如何利用C++标准模板库(STL)中的string类find()和rfind()方法来高效解决字符串匹配问题,包括查找特定子串在目标字符串中的出现次数。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在解决这道题之前先介绍一下string类find()的调用。

string str; int found;

str.find("needles are small",found+1,6);从found+1的位置开始

在str中查找"needles are small"字符串的前6个字符 也就是"needle"


str.find(str2) 在str中查找str2字符串 若找不到则返回string::npos

rfind() 类似,只是从反向查找

#include <iostream>
#include <algorithm>
#include <vector>
#include <string>
using namespace std;
int main()
{

	int n;cin>>n;
	while(n--)
	{

		string s1,s2;
		cin>>s1>>s2;
		int found=0,count=0;
		found=s2.find(s1);
		while(found!=string::npos)
		{	
			count++;
			found=s2.find(s1,found+1);
		}
		cout<<count<<endl;
	}
}


如要查找str2在str中出现多少次时 需要循环查找

        found=s2.find(s1);  第一句find一定要写在循环外面 不然很难去控制while的结束条件
        while(found!=string::npos)
        {
            count++;
            found=s2.find(s1,found+1); 在上次查找的基础上加一位继续查找
        }

一开始看以为是KMP的问题 后来发现string的STL就很容易解决问题直接上代码

其实很水到爆炸的题 我居然还在输入N后加了个getchar()导致CE了一次 也是无语。。。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值