C言語のSTRCAT / strlen関数/関数strcmp / strcpyの

二つの主要な考慮事項:

  1. 使用の戻り値の利便性。
  2. ボーダー、nullを判断。

strcatの

char *m_strcat(char *des, const char *src)
{
    assert((des != NULL) && (src != NULL));
    char *add = des;
    while (*des != '\0')
        ++des;
    while (*des++ = *src++)
        ;
    return add;
}

strlen関数

int m_strlen(const char *str)
{
    assert(str != NULL);
    int len = 0;
    while (*str != '\0')
    {
        ++str;
        ++len;
    }
    return len;
}

strcmpの

int m_strcmp(const char *des, const char *src)
{
    // return 0 des==src , + des>src , - des<src
    assert((des != NULL) && (src != NULL));
    while ((*des) == (*src))
    {
        if (*des == '\0')
            return 0;
        ++des;
        ++src;
    }
    return *des - *src;
}

strcpyの

char *m_strcpy(char *des, const char *src)
{
    assert((des != NULL) && (src != NULL));
    char *add = des;
    while ((*des++ = *src++) != '\0')
        ;
    return add;
}

おすすめ

転載: www.cnblogs.com/ruoh3kou/p/11230546.html