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

C語言字符串庫函數手寫實現:strlen、strcpy、strcat、strcmp 等核心函數

     編輯:關於C語言

C語言字符串庫函數手寫實現:strlen、strcpy、strcat、strcmp 等核心函數

從零手寫標準庫字符串函數,深入理解指針操作與字符串結構。

函數清單與實現要點

函數標準庫對應核心邏輯
fun1strlen迴圈計數至 \0
fun2strlen指針相減:end - start
fun3strlen遞歸:1 + strlen(s+1)
fun4strncat定位 dest 末尾,拷貝 n 字符
fun5strstr雙重迴圈匹配子串
fun6strstr優化版:外層遍歷 s1,內層匹配 s2
fun7strcpywhile(*d++ = *s++); 一行實現
fun8strcmp逐字符比較,差值即結果
fun9memcpy逐字節拷貝,不處理重疊
fun10memmove處理重疊:向前/向後拷貝

經典單行實現賞析

// strcpy
char *strcpy(char *d, const char *s) {
    char *ret = d;
    while (*d++ = *s++);
    return ret;
}

// strcmp
int strcmp(const char *s1, const char *s2) {
    while (*s1 == *s2) {
        if (*s1 == '\0') return 0;
        s1++; s2++;
    }
    return *s1 - *s2;
}

學習建議

  • 親手敲寫每個函數,觀察指針移動與邊界條件。
  • 對比 memcpy 與 memmove 的重疊處理差異。
  • 理解 const 正確性:源字符串不應被修改。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved