C语言字符串查找函数实现:查找子串位置并返回

本文将详细讲解如何实现一个简单的C语言函数find(char* str, char* sub),该函数的功能是判断子串sub是否在字符串str中,如果找到则返回子串sub在字符串str中的起始位置,否则返回-1。

函数实现:

int find(char* str, char* sub) {
    if (str == NULL || sub == NULL) {
        return -1;
    }
    int strLen = strlen(str);
    int subLen = strlen(sub);
    if (subLen == 0) {
        return 0;
    }
    for (int i = 0; i <= strLen - subLen; i++) {
        int j;
        for (j = 0; j < subLen; j++) {
            if (str[i + j] != sub[j]) {
                break;
            }
        }
        if (j == subLen) {
            return i;
        }
    }
    return -1;
}

测试用例:

  1. str = '', sub = '',返回0
  2. str = 'abc', sub = '',返回0
  3. str = '', sub = 'abc',返回-1
  4. str = 'abc', sub = 'ab',返回0
  5. str = 'abc', sub = 'bc',返回1
  6. str = 'abc', sub = 'cd',返回-1
  7. str = 'abcabc', sub = 'bc',返回1
  8. str = 'abcdefg', sub = 'def',返回3
  9. str = 'abcabc', sub = 'bc',返回1
  10. str = 'aaa', sub = 'a',返回0

代码解释:

  1. 函数首先判断strsub是否为空指针,如果为空则返回-1。
  2. 然后获取strsub的长度,如果sub为空字符串,则直接返回0。
  3. 使用两层循环遍历strsub,外层循环遍历str,内层循环遍历sub
  4. 在内层循环中,比较strsub对应位置的字符,如果字符不匹配,则跳出内层循环。
  5. 如果内层循环能够完整遍历sub,说明子串sub在字符串str中,返回子串sub在字符串str中的起始位置。
  6. 如果外层循环遍历完str,仍然没有找到子串sub,则返回-1。

总结:

本文详细讲解了C语言中实现字符串查找函数find(char* str, char* sub)的逻辑,并提供了多个测试用例,帮助理解代码的实现和功能。希望本文能够帮助您更好地理解字符串查找算法。

C语言字符串查找函数实现:查找子串位置并返回

原文地址: https://www.cveoy.top/t/topic/n93d 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录