欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

C常用库函数实现

程序员文章站 2022-03-23 20:06:27
C常用库函数实现 // ---------- strlen ------------- int strlen(char *t){ int length = 0;...
C常用库函数实现
// ---------- strlen -------------
int strlen(char *t){
    int length = 0;
    if(t == NULL)
        return -1;

    while (*t != '\0') {
        t++;
        length++;
    }
    return length;
}

size_t strlen(const char *s)
{
    const char *sc;

    for (sc = s; *sc != '\0'; ++sc);

    return sc - s;
}

// ---------- trim -------------

void ltrim ( char *s )
{
    char *p;
    p = s;
    while ( *p == ' ' || *p == '\t' ) {p++;}
    strcpy ( s,p );
}

void rtrim ( char *s )
{
    int i;

    i = strlen ( s )-1;
    while ( ( s[i] == ' ' || s[i] == '\t' ) && i >= 0 ) {i--;};
    s[i+1] = '\0';
}

void trim ( char *s )
{
    ltrim ( s );
    rtrim ( s );
}

// ---------- strcpy -------------

char *strcpy(char *dest, const char *src)
{
    char *tmp = dest;

    while ((*dest++ = *src++) != '\0');

    return tmp;
}

// ---------- strcat -------------

char *strcat(char *dest, const char *src)
{
    char *tmp = dest;

    while (*dest)
        dest++;
    while ((*dest++ = *src++) != '\0');

    return tmp;
}

// ---------- strstr -------------

char *strstr(const char *s1, const char *s2)
{
    int l1, l2;

    l2 = strlen(s2);
    if (!l2)
        return (char *)s1;
    l1 = strlen(s1);
    while (l1 >= l2) {
        l1--;
        if (!memcmp(s1, s2, l2))
            return (char *)s1;
        s1++;
    }

    return NULL;
}


// ---------- memcmp -------------

int memcmp(char *cs, char *ct, size_t count)
{
    char *su1, *su2;
    int res = 0;

    for (su1 = cs, su2 = ct; 0 < count; ++su1, ++su2, count--)
        if ((res = *su1 - *su2) != 0)
            break;
    return res;
}

// ---------- strcmp -------------

int strcmp(const char *cs, const char *ct)
{
    unsigned char c1, c2;

    while (1) {
        c1 = *cs++;
        c2 = *ct++;
        if (c1 != c2)
            return c1 < c2 ? -1 : 1;
        if (!c1)
            break;
    }

    return 0;
}