子串匹配--------c++

  • 匹配子串在主字符串中的开始位置
cpp 复制代码
#include <stdio.h>
#include <string.h>
size_t substringMatching(const char* haystack, const char* needle) 
{
	size_t haystack_len = strlen(haystack);
	size_t needle_len = strlen(needle);
	printf("haystack_len:%zu\n", haystack_len);
	printf("needle_len:%zu\n", needle_len);

	for (size_t i = haystack_len; i >= needle_len; --i) 
	{
		size_t j;
		for (j = 0; j < needle_len; ++j) 
		{
			if ((char)haystack[i - needle_len + j] != (char)needle[j]) 
			{
				break;
			}
		}
		if (j == needle_len) {
			return i - needle_len; // 返回子串在主串中的位置
		}
	}

	return (size_t)-1; // 未找到子串,返回-1
}

int main() 
{
	const char* haystack = "sdc\x0D\x0A\x4F\x4B\x00sac\xFF\xAB\xCD";
	const char* needle = "OK"; // 要查找的子串:OK十六进制为0x4F0x4B

	size_t result = substringMatching(haystack, needle);
	if (result != (size_t)-1) 
	{
		printf("Substring found at position: %zu\n", result);
	}
	else 
	{
		printf("Substring not found.\n");
	}

	return 0;
}
相关推荐
White_Can10 分钟前
《C++11:智能指针》
c++·c++11·智能指针
无限进步_10 分钟前
【数据结构&C语言】对称二叉树的递归之美:镜像世界的探索
c语言·开发语言·数据结构·c++·算法·github·visual studio
im_AMBER23 分钟前
Leetcode 98 从链表中移除在数组中存在的节点
c++·笔记·学习·算法·leetcode·链表
CSDN_RTKLIB23 分钟前
C++取模与取余
开发语言·c++
星河耀银海40 分钟前
C++开发入门——环境搭建与第一个程序
开发语言·c++·策略模式
_OP_CHEN2 小时前
【算法基础篇】(四十四)数论之欧拉定理与扩展欧拉定理深度解析:从降幂到超大规模幂运算
c++·算法·蓝桥杯·算法竞赛·欧拉定理·扩展欧拉定理·acm/icpc
liulilittle2 小时前
DeepWiki: OPENPPP2 工程价值
网络·c++·网络协议·ai·信息与通信·通信
星河耀银海2 小时前
C++面向对象编程:从基础到实战
开发语言·c++
Ccjf酷儿2 小时前
C++语言程序设计 (郑莉)第三章 函数
开发语言·c++
石去皿2 小时前
从本地知识库到“活”知识——RAG 落地全景指南
c++·python·大模型·rag