能否不使用<string.h>库实现C语言字符串查找函数?如何实现?
问题
我编写了一个C语言函数str_find,函数签名为int str_find(char* needle, char* haystack),接收两个char*类型参数。若第二个参数haystack包含第一个参数needle,则返回其起始索引;否则返回-1。当前代码引入了<string.h>库,请问是否可以不使用该库实现该函数?具体方法是什么?
现有代码如下:
#include <stdio.h> #include <string.h> int str_find(char* needle, char* haystack) { int needle_length = strlen(needle); int haystack_length = strlen(haystack); if (needle_length == 0) { return 0; } if (haystack_length == 0) { return -1; } int par_1 = 0; for(int par_2 = 0; par_2 < haystack_length; par_2++) { if (haystack[par_2] == needle[0]) { for (par_1 = 0; par_1 < needle_length; par_1++) if (haystack[par_2 + par_1]) break; if (par_2 == needle_length) return par_2; } } return -1; } int main() { printf("%d\n",str_find("=","-h=123")); return 0; }
回答
完全可以不使用<string.h>库实现这个函数,核心是自己实现字符串长度计算,同时修正原代码里的匹配逻辑bug。
具体实现方法
- 替代
strlen:自己写一个计算字符串长度的函数,原理是遍历字符串直到遇到终止符'\0',统计字符数量。 - 修复匹配逻辑:原代码的内层循环和判断条件存在错误,无法正确完成子串匹配,需要重新实现逐字符对比的匹配逻辑。
改进后的完整代码
#include <stdio.h> // 自定义字符串长度计算函数,替代<string.h>中的strlen int my_strlen(char* str) { int len = 0; while (str[len] != '\0') { len++; } return len; } int str_find(char* needle, char* haystack) { int needle_len = my_strlen(needle); int haystack_len = my_strlen(haystack); // 空模式串按需求返回0 if (needle_len == 0) { return 0; } // 空主串且模式串非空,返回-1 if (haystack_len == 0) { return -1; } // 遍历主串,仅需遍历到haystack_len - needle_len位置,避免无效循环 for (int i = 0; i <= haystack_len - needle_len; i++) { int is_match = 1; // 逐字符对比模式串和主串当前位置的子串 for (int j = 0; j < needle_len; j++) { if (haystack[i + j] != needle[j]) { is_match = 0; break; } } if (is_match) { return i; // 匹配成功,返回起始索引 } } // 未找到匹配,返回-1 return -1; } int main() { printf("%d\n", str_find("=", "-h=123")); // 输出2,符合预期 printf("%d\n", str_find("123", "-h=123")); // 输出3 printf("%d\n", str_find("abc", "-h=123")); // 输出-1 return 0; }
关键细节说明
- 自定义
my_strlen:完全模拟strlen的功能,不需要依赖标准库,通过循环检测字符串终止符实现长度计算。 - 优化循环范围:主串遍历到
haystack_len - needle_len即可,因为剩下的字符长度不足以容纳模式串,避免不必要的循环。 - 正确匹配逻辑:内层循环逐个对比字符,只要有一个字符不匹配就终止当前检查,全部匹配则返回当前索引,逻辑清晰且正确。
内容的提问来源于stack exchange,提问作者onix012
相关产品推荐
相关产品推荐

