首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> 關於C語言

C語言手寫 strstr:子串查找返回後綴字符串

     編輯:關於C語言

C語言手寫 strstr:子串查找返回後綴字符串

實現 my_strstr:在主串中查找子串,找到返回子串後的剩餘字符串(即標準 strstr 行為),未找到返回 NULL。

修正後的標準實現

#define _CRT_SECURE_NO_WARNINGS 1
#include <stdio.h>
#include <assert.h>
#include <stdlib.h>

char *my_strstr(const char *haystack, const char *needle) {
    assert(haystack && needle);
    
    if (*needle == '\0') return (char *)haystack;
    
    const char *h = haystack;
    while (*h) {
        const char *h_start = h;
        const char *n = needle;
        
        while (*h && *n && *h == *n) {
            h++;
            n++;
        }
        
        if (*n == '\0') {
            return (char *)h_start;  // 返回匹配起點
        }
        
        h = h_start + 1;  // 關鍵:回溯到下一個起始位置
    }
    
    return NULL;
}

int main() {
    char *s1 = "abcdeff";
    char *s2 = "abc";
    char *ret = my_strstr(s1, s2);
    printf("結果:%s\n", ret ? ret : "NULL");
    system("pause");
    return 0;
}

運行結果

結果:abcdeff

關鍵修正說明(針對原代碼問題)

  • 原代碼變量 s、q 未聲明,邏輯混亂
  • 內層匹配需保存 h_start 作為潛在返回值
  • 匹配失敗時必須 h = h_start + 1,不能直接 h++
  • 空子串語義:返回主串開頭

測試矩陣

主串子串返回值說明
"abcdeff""abc""abcdeff"前綴匹配
"abcdeff""de""deff"中間匹配
"abcdeff""xyz"NULL不存在
"aaaaa""aaa""aaaaa"返回首個匹配
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved