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

C 語言手寫四大內存字符串函數:strncmp、strncat、memset、memcmp

     編輯:關於C語言

1. strncmp

int my_strncmp(const char *s1, const char *s2, size_t n) {
    assert(s1 && s2);
    while (--n && *s1 && *s1 == *s2) { s1++; s2++; }
    return *s1 - *s2;
}

2. strncat

char *my_strncat(char *dst, const char *src, size_t n) {
    assert(dst && src);
    char *ret = dst;
    while (*dst) dst++;
    while (n-- && *src) *dst++ = *src++;
    *dst = '\0';
    return ret;
}

3. memset

void *my_memset(void *s, int ch, size_t n) {
    assert(s);
    void *ret = s;
    while (n--) *(char*)s++ = (char)ch;
    return ret;
}

4. memcmp

int my_memcmp(const void *s1, const void *s2, size_t n) {
    const char *a = s1, *b = s2;
    while (--n && *a && *a == *b) { a++; b++; }
    return *a - *b;
}

測試主程序

int main() {
    char a[]="abcdef", b[]="abcdeg";
    printf("strncmp: %d\n", my_strncmp(a,b,3)); // 0
    char buf[20]="hi "; my_strncat(buf,"there",3); printf("strncat: %s\n",buf); // hi the
    char c[10]; my_memset(c,'X',5); c[5]='\0'; printf("memset: %s\n",c); // XXXXX
    printf("memcmp: %d\n", my_memcmp(a,b,6)); // 負值
    return 0;
}
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved