子串匹配--------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;
}
相关推荐
-森屿安年-35 分钟前
LeetCode 283. 移动零
开发语言·c++·算法·leetcode
散峰而望1 小时前
C++数组(一)(算法竞赛)
c语言·开发语言·c++·算法·github
FuckPatience4 小时前
C++ 常用类型写法和全称
开发语言·c++
__BMGT()4 小时前
参考文章资源记录
开发语言·c++·qt
ouliten5 小时前
C++笔记:std::string_view
开发语言·c++·笔记
玫瑰花店5 小时前
万字C++中锁机制和内存序详解
开发语言·c++·算法
D_evil__5 小时前
[C++高频精进] 文件IO:文件流
c++
西幻凌云5 小时前
认识STL序列式容器——List
开发语言·c++·stl·list·序列式容器
Elias不吃糖6 小时前
LeetCode每日一练(209, 167)
数据结构·c++·算法·leetcode
Want5956 小时前
C/C++跳动的爱心②
c语言·开发语言·c++