C++/C#搜索字符串的for循环算法(c++遍历字符串的每个字符)

C++/C#搜索字符串的for循环算法(c++遍历字符串的每个字符)

编码文章call10242025-02-01 3:39:4033A+A-

1.前言
InfinityHook里面有个搜索字符串的算法比较有意思,如果是在C#里面一行代码即可搜索。但C++则是承担了底层的实现。如何实现的呢?本篇来看下

2.概括
在source里面搜索pattern相同字符串,分别看下C#和C++代码

C#代码:

static void Main(string[] args){ string source= "39 39 39 48 33 33 33 33 33 33 48 85 C0 74 39 39 39"; string pattern = "48 33 33 33 33 33 33 48 85 C0 74"; string result=source.Substring(source.IndexOf(pattern),pattern.Length-5); Console.WriteLine(result); }

C++代码

#include<stdio.h>int main(int argc, char** argv){ /* 案例算法:在source数组里面找到pattern数组里面相同的字符。 */ //数组source里面包含了数组patteren的字符 char source[] = "\x39\x39\x39\x48\x33\x33\x33\x33\x33\x33\x48\x85\xC0\x74\x39\x39\x39"; char pattern[] = "\x48\x33\x33\x33\x33\x33\x33\x48\x85\xC0\x74"; int sourcelength = sizeof(source) - 1; int patternlength = sizeof(pattern) - 1;
char wildcard = 0x33;
//这里source数组长度减去pattern数组长度是为免得下面的for多循环patternlength个体长度 for (int i = 0; i < sourcelength - patternlength; i++) { //found表示如果pattern里面的字符不等于0x33也不等于source数组的的某个字符,直接跳过本轮for循环。 //因为没有找到匹配的 bool found = true; //如果这个for循环到底,found依旧为true,说明找到了,相同字符串的起始索引。 for (int j = 0; j < patternlength; j++) { //这里的判断分为几种情况 // 1. pattern[j] != wildcard==true pattern[j] != (source[i + j] 直接跳过本轮循环,因为没有找到 // 2. pattern[j] != wildcard==true pattern[j] = = (source[i + j] 表示找到了相同字符串,继续 // 3. pattern[j] == wildcard==true 如果是这种情况,第一个判断为false,第二个就不用判断了,继续下一次循环 if (pattern[j] != wildcard && pattern[j] != (source[i + j])) { found = false; break; } } if (found != false) { //这个地方的i索引是第一个for循环+第二个for循环 //在source字符数组里面找到pattern数组相同的字符的其实索引 //这里以为i已经在索引3的位置了,所以下面的循环只能到pattern数组的第二个\x48.后面的3个超了数组的索引极限 // 比如 patternlength+i for (int k = i; k < patternlength; k++) { printf("%x\n", source[k]); } break; } } getchar();}

可以看到C#高度封装,比较简单的几行代码,然C++则多了更多的代码。但C++的算法比较奇特,这里记录下。


点击这里复制本文地址 以上内容由文彬编程网整理呈现,请务必在转载分享时注明本文地址!如对内容有疑问,请联系我们,谢谢!
qrcode

文彬编程网 © All Rights Reserved.  蜀ICP备2024111239号-4