字符串的朴素模式匹配算法——c语言实现

int findbyindex(char* s, char* t, int index);

此自定义函数返回字符串t在s字符串中的首个字符的下标位置

C 库函数 size_t strlen(const char *str) 

计算字符串 str 的长度,直到空结束字符,但不包括空结束字符

该函数返回字符串的长度。

代码实现

#include<stdio.h>
#include<string.h>
int findbyindex(char* s, char* t, int index)
{
	if (index <= 0 || s == NULL || t == NULL)
		return -1;//输入出错
	int s_index = index;//用于遍历s字符串的下标
	int t_index = 0;
	int s_len = strlen(s);
	int t_len = strlen(t);
	while (s_index<=(s_len-1)&&t_index<=(t_len-1))
	{
		if (s[s_index] == t[t_index])//相等继续遍历
		{
			s_index++;
			t_index++;
		}
		else//不相等
		{
			s_index = s_index - t_index + 1;//下标回到开始比对的位置的下一个位置
			t_index = 0;
		}
	}
	if (t_index == t_len)
	{
		//找到了
		return s_index - t_len;//返回下标开始比对的位置
	}
	else
	{
		return 0;
	}


}
int main()
{
	    char s[15] = "hellanuluoss";
		char t[7] = "luo";
		int back=findbyindex(s, t,0);
		printf("t字符串在s字符串中的下标位置%d", back);
		return 0;

}

运行结果

 

-数据结构练习代码如有错误欢迎指正

-参考书籍《大话数据结构》

 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值