1 #include <stdio.h> 2 #include <stdlib.h> 3 #include <string.h> 4 5 /* 6 _Check_return_ _Ret_maybenull_ 7 inline char* __CRTDECL strstr(_In_z_ char* const _String, _In_z_ char const* const _SubString) 8 { 9 return const_cast<char*>(strstr(static_cast<char const*>(_String), _SubString)); 10 } 11 */ 12 13 /* 14 对于字符串查找问题,可使用双重 for 循环解决, 15 效率更高的则为 KMP 算法。双重 for 循环的使用较有讲究, 16 因为这里需要考虑目标字符串比源字符串短的可能。 17 对目标字符串的循环肯定是必要的,所以可以优化的地方就在于如何访问源字符串了。 18 简单直观的解法是利用源字符串的长度作为 for 循环的截止索引, 19 这种方法需要处理源字符串中剩余长度不足以匹配目标字符串的情况, 20 而更为高效的方案则为仅遍历源字符串中有可能和目标字符串匹配的部分索引。 21 22 */ 23 char *mystrstr1(char* const _String, char const* const _Substring)// 下标法 24 { 25 if (_String == NULL || _Substring == NULL) 26 { 27 return NULL; 28 } 29 char *pres = NULL; 30 int strLength = strlen(_String); // 母串的长度 31 int subLength = strlen(_Substring); // 子串的长度 32 33 for (int i = 0; i < strLength - subLength + 1; i++)// 获取要前进的尺度 34 { 35 int flag = 1; // 假定相等 36 for (int j = 0; j < subLength; j++) 37 { 38 39 if (_Substring[j] != _String[i+j])// 循环对比 40 { 41 flag = 0; 42 break; 43 } 44 } 45 if (flag) 46 { 47 pres = _String + i; // 找到的地址 48 return pres; 49 } 50 } 51 52 return pres; 53 54 } 55 56 57 58 char *mystrstr2(char * const _String, char * const _Substring)// 指针法 59 { 60 if (_String == NULL || _Substring == NULL) 61 { 62 return NULL; 63 } 64 char *pbak = _String; // 备份首地址 65 while (*pbak != '