子串匹配--------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;
}
相关推荐
WL学习笔记2 小时前
继承(C++)
c++·继承
lcj25112 小时前
【日志系统实战】同步/异步日志系统:手写日志等级模块,吃透enum class与7大分级,面试不慌
c++·设计模式·面试·c++11·日志系统
zmzb01032 小时前
C++课后习题训练记录Day216
数据结构·c++·算法
西西弗Sisyphus3 小时前
C++ 最小 Agentic Loop 实现 - 开始实现 完整的内容
开发语言·c++
天威?*4 小时前
团体程序设计天梯练习集L3-001 凑零钱
数据结构·c++
充值内卷5 小时前
Varsar:一个 5.7 MB 的免安装文件对比工具
c++·比较工具
wo_jack6 小时前
C++ 入门笔记(二十):stack / queue 的模拟实现 —— 适配器与 deque 底层
c++·stl·deque·queue·stack
_dindong6 小时前
仿muduo库实现高并发服务器 -通用类型Any类型的实现
服务器·c++
不在逃避q7 小时前
用生活里的小场景,一键打开 C++ 编程入门大门
开发语言·c++·生活
YSL0701247 小时前
C++string类详解
开发语言·数据结构·c++