字符串的查找的3种方法

KMP

#include <iostream>
#include <cstring>
#include <algorithm>

using namespace std;
const int N = 1e5 + 10, M = 1e6 + 10;
char s[M],p[N];
int ne[M];
int main()
{
    int n,m;
    cin>>n>>p + 1>>m>>s + 1;
    
    for(int i = 2, j = 0; i <= n; i ++)
    {
        while(j && p[i] != p[j + 1])j = ne[j];
        if(p[i] == p[j + 1])j ++;
        ne[i] = j; 
    }
    
    
    for(int i = 1, j = 0; i <= m; i ++)
    {
        while(j && s[i] != p[j + 1])j = ne[j];
        if(s[i] == p[j + 1])j ++;
        if(j == n)
        {
            cout<<i - n<<' ';
            j = ne[j];
        }
    }
    
    
}

ne[j]存的是对于模板串p,当前最大后缀与前缀相等的长度,有了这个长度,可以在s[i] != p[j + 1]时,让p串前面保留的信息尽量的多
推荐下标从1开始写,因为这样ne数组里面存的长度就是下次返回的下标


strstr(s, p)库函数(必须是char[])

s中有p则返回第一次出现的地址,否则返回NULL

char str[100] = "abcdefg";
char p[100] = "deq";
if(strstr(str,p))
{
	int pos = strstr(str, p ) - str;
	cout<<pos<<endl;
}

string 里面的 find()函数

存在返回位置,不存在返回s.npos

	string s = "abcdefg";
	string p = "bcd";
	if(s.find(p) != s.npos)
	{
		int pos = s.find(p);
		cout<<pos<<endl;
	}
	else cout<<"no";

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
可以使用字符串的 find 和 rfind 方法查找一个字符串在另外一个字符串指定范围中首次和最后一次出现的位置。 假设要在字符串 str 中查找子串 sub 在指定范围 [start, end) 中首次和最后一次出现的位置,可以使用以下代码: ``` start = 0 # 起始位置 end = 10 # 结束位置(不包含) first_pos = str.find(sub, start, end) last_pos = str.rfind(sub, start, end) ``` 其中,find 方法返回子串 sub 在字符串 str 中首次出现的位置,如果不存在则返回 -1。rfind 方法返回子串 sub 在字符串 str 中最后一次出现的位置,如果不存在则返回 -1。 注意,指定范围 [start, end) 是一个左闭右开区间,表示从字符串的下标 start 开始(包含 start 对应的字符),到下标 end-1 结束(不包含 end 对应的字符)的字符范围。 例子: ``` str = "hello, world!" sub = "l" start = 0 end = 5 first_pos = str.find(sub, start, end) last_pos = str.rfind(sub, start, end) print("First position of '{}' in '{}' between {} and {}: {}".format(sub, str, start, end, first_pos)) print("Last position of '{}' in '{}' between {} and {}: {}".format(sub, str, start, end, last_pos)) ``` 输出: ``` First position of 'l' in 'hello, world!' between 0 and 5: 2 Last position of 'l' in 'hello, world!' between 0 and 5: -1 ``` 在这个例子中,子串 "l" 在字符串 "hello, world!" 中在指定范围 [0, 5) 中首次出现的位置是 2,最后一次出现的位置是 -1(表示不存在)。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值