子串匹配--------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;
}
相关推荐
Dream it possible!1 小时前
LeetCode 面试经典 150_图的广度优先搜索_最小基因变化(93_433_C++_中等)(广度优先搜索(BFS))
c++·leetcode·面试·广度优先
steins_甲乙2 小时前
C++并发编程
开发语言·c++
南莺莺3 小时前
二叉排序树的创建和基本操作---C++实现
数据结构·c++·算法··二叉排序树
仰泳的熊猫3 小时前
1061 Dating
数据结构·c++·算法·pat考试
Fcy6483 小时前
二叉搜索树(C++实现)
开发语言·数据结构·c++·二叉搜索树
surtr13 小时前
Round 1019(div2) CD
数据结构·c++·算法·贪心算法·stl
Tim_104 小时前
【C++入门】02、C++程序初识
开发语言·c++
小小晓.4 小时前
Pinely Round 2 (Div. 1 + Div. 2)
c++·算法
清风拂山岗 明月照大江4 小时前
简单文件 IO 示例:使用系统调用读写文件
开发语言·c++·算法