子串匹配--------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;
}
相关推荐
clint45612 小时前
C++进阶(1)——前景提要
c++
夜悊16 小时前
C++代码示例:进制数简单生成工具
c++
郝学胜_神的一滴18 小时前
CMake 021: IF 条件判据详诠
c++·cmake
_wyt0011 天前
洛谷 B3930 [GESP202312 五级] 烹饪问题 题解
c++·gesp
玖玥拾1 天前
C/C++ 数据结构(七)栈、容器适配器
c语言·数据结构·c++··容器适配器
один but you2 天前
constexpr函数
c++
凡人叶枫2 天前
Effective C++ 条款41:了解隐式接口和编译期多态
java·开发语言·c++·effective c++
凡人叶枫2 天前
Effective C++ 条款42:了解 typename 的双重意义
java·linux·服务器·c++
小胖xiaopangss2 天前
BRpc使用
c++·rpc
-森屿安年-2 天前
63. 不同路径 II
c++·算法·动态规划