模擬實現:strlen,strcat,strchr,strcpy,strcat...

模擬實現的字符串處理函數:
strlen,strcat,strncat,strchr,strrchr,strcpy,strncpy

1.strlen,求字符串的長度,不算‘/0’

size_t mystrlen(const char *string)
{
    const char *p = string;
    while (*p++)
    {}
    return(p - string - 1);
}

2.strcat,拼接字符串

char *mystrcat(char *dest, const char *source)//兩個字符串拼接
{
    char *address = dest;
    assert((*dest != NULL) && (*source != NULL));
    while (*dest++)
    {}
    while (*(dest++) = *(source++))
    {}
    return address;
}

3.strncat,拼接字符串,把第二串字符串前count字符拼接到第一個字符串後面

char *mystrncat(char *dest, const char* source,size_t count)//把2字符串前count個接到1字符串後面
{
    char *address = dest;
    assert((*dest != NULL) && (*source != NULL));
    while (*dest != '\0')
    {
        dest++;
    }
    while (count && (*dest++ = *source++))
    {
        count--;
    }
    *dest = '\0';
    return address;
}

4.strchr,找出第一次出現字符C的位置

const char * mystrchr(const char * string,char C)//第一次出現字符的位置,如果沒有返回NULL
{
    assert(*string != NULL);
    while (*string)
    {
        if (*string == C)
            return string;
        string++;
    }
    return NULL;
}

5.strrchr,返回字符C最後出現在字符串的位置

const char * mystrrchr(const char * string, char C) //最後一個字符出現的位置,如果沒有返回NULL
{
    const char* tmp = NULL;
    assert(*string != NULL);
    while (*string)
    {
        if (*string == C)
            tmp = string;
        string++;
    }
    return tmp;
}

6.strcpy,字符串拷貝

char * mystrcpy(char *dest, const char *source)
{
    char *address = dest;
    assert((dest != NULL)&&(source != NULL));
    while (*dest++ = *source)
    {}
    return address;
}

7.strncpy,字符串拷貝,拷貝源字符串count個字符到目的字符串

char *mystrncpy(char *dest, const char *source, size_t count)
{
    assert((dest != NULL) && (source != NULL));
    char *address = dest;
    while (count--)
    {
        *dest++ = *source++;
    }
    *dest = '\0';
    return address;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章