匹配字符串

问题描述:
分别输入字符串1和字符串2,若在字符串1中匹配到字符串2,则输出匹配位置。

(1)BF算法

代码展示:

#include "pch.h"
#include <iostream>
#include <String>
using namespace std;
#define MaxSize 100
typedef struct
{
	char data[MaxSize];
	int length;
}SqString;

int BF(SqString s,SqString t)
{
	int i = 0,  j = 0;
	while (i<s.length&&j<t.length)
	{
		if (s.data[i]==t.data[j])
		{
			i++;
			j++;
		}
		else
		{
			i = i - j + 1;
			j = 0;
		}
	}
	if (j >= t.length)
		return i - t.length;
	else
	{
		return -1;
	}
}

int main()
{
	SqString sqstring1,sqstring2;
	string str1, str2;
	cout << "BF算法\n请输入字符串1:";
	cin >> str1;
	cout << "请输入字符串2:";
	cin >> str2;
	sqstring1.length = str1.length();
	sqstring2.length = str2.length();
	strcpy_s(sqstring1.data,str1.c_str());
	strcpy_s(sqstring2.data,str2.c_str());
	int x=BF(sqstring1,sqstring2);//接收返回值,判断
	if (x == -1)
	{
		cout << "未在字符串1中匹配到字符串2!" << endl;
	}
	else
	{
		cout << "字符串2在字符串1中的位置是:" << x+1 << endl;//+1输出真实坐标
	}
	return 0;
}

运行结果:
在这里插入图片描述

(2)KMP算法

代码展示:

#include "pch.h"
#include <iostream>
#include <String>
using namespace std;
#define MaxSize 100
typedef struct
{
	char data[MaxSize];
	int length;
}SqString;

void GetNextval(SqString t,int nextval[])//由模式串t求出nextval值
{
	int j = 0, k = -1;
	nextval[0] = -1;
	while (j < t.length)
	{
		if (k == -1 || t.data[j] == t.data[k])
		{
			j++;
			k++;
			if (t.data[j] != t.data[k])
				nextval[j] = k;
			else
				nextval[j] = nextval[k];
		}
		else
		{
			k = nextval[k];
		}
	}
}

int KMPIndexl(SqString s, SqString t)
{
	int nextval[MaxSize], i = 0, j = 0;
	GetNextval(t, nextval);
	while (i < s.length&&j < t.length)
	{
		if (j == -1 | s.data[i] == t.data[j])
		{
			j++;
			i++;
		}
		else
			j = nextval[j];
	}
	if (j >= t.length)
		return i - t.length;
	else
		return -1;
}


int main()
{
	SqString sqstring1, sqstring2;
	string str1, str2;
	cout << "KMP算法\n请输入字符串1:";
	cin >> str1;
	cout << "请输入字符串2:";
	cin >> str2;
	sqstring1.length = str1.length();
	sqstring2.length = str2.length();
	strcpy_s(sqstring1.data, str1.c_str());
	strcpy_s(sqstring2.data, str2.c_str());
	int x = KMPIndexl(sqstring1, sqstring2);//接收返回值,判断
	if (x == -1)
	{
		cout << "未在字符串1中匹配到字符串2!" << endl;
	}
	else
	{
		cout << "字符串2在字符串1中的位置是:" << x + 1 << endl;//+1输出真实坐标
	}
	return 0;
}

运行结果:
在这里插入图片描述

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值