C言語基礎3:文字列関数の実現(筆記試験問題)

7847 ワード

1、文字列の長さ
int strlen(const char *str)   
{   
    assert(str != NULL);   
    int len = 0;   
    while (*str ++ != '\0')   
        ++ len;   
    return len;   
}

2、文字列コピー
// strncpy        
char *strncpy(char *to, const char *from, size_t count)
{
    assert((to != NULL) && (from != NULL));
    char * result = to;
    while(count--)
    {
        if(*from != '\0')
        {
            *to++ = *from++;
        }
        else
        {
            *to++ = '\0';
        }
    }
    return result;       
}

//     
char *strcpy(char *to, const char *from)
{
    assert((to != NULL) && (from != NULL));
    char * result = to;
    while( (*to++ = *from++) != '\0')
        NULL;
    return result;       
}

3、memset():指定メモリ領域の先頭countバイトを文字cに設定
void * memset(void* buffer, int c, size_t count)
{
    assert(buffer != NULL);
    char * p = (char *)buffer;
    while(count--)
        *p++ = (char)c;
    return buffer;
}

4、検索文字列sに初めて出現する文字cの位置
char *strchr(char *str, int c)   
{   
    assert(str != NULL);   
    for (; *str != (char)c; ++ str)
    {   
        if (*str == '\0')   
            return NULL;   
        return str;
    }   
}   

5、文字列接続
//        
char *strcat(char *strDes, const char *strSrc)   
{   
    assert((strDes != NULL) && (strSrc != NULL));   
    char *address = strDes;   
    while (*strDes != '\0')   
        ++ strDes;   
    while ((*strDes ++ = *strSrc ++) != '\0')   
        NULL;   
    return address;   
}

//        
char *strncat(char *strDes, const char *strSrc, unsigned int count)   
{   
    assert((strDes != NULL) && (strSrc != NULL));   
    char *address = strDes;   
    while (*strDes != '\0')   
        ++ strDes;   
    while (count -- && *strSrc != '\0' )   
        *strDes ++ = *strSrc ++;   
    *strDes = '/0';   
    return address;   
}   

6、文字列が初めて現れる場所を検索する
char *strstr(const char *strSrc, const char *str)   
{   
    assert(strSrc != NULL && str != NULL);   
    const char *s = strSrc;   
    const char *t = str;   
    for (; *strSrc != '\0'; ++ strSrc)   
    {   
        for (s = strSrc, t = str; *t != '\0' && *s == *t; ++s, ++t)   
        {  
            if (*t == '\0')
            {
                return NULL;
            }   
            return (char *) strSrc;  
        } 
    }   
    return NULL;   
} 

7、文字列を新しい場所にコピーする
char *strdup_(char *strSrc)
{     
    if(strSrc!=NULL)     
    {     
        char *start=strSrc;     
        int len=0;     
        while(*strSrc++!='\0')     
            len++;     

        char *address=(char *)malloc(len+1);     
        assert(address != NULL);  

        while((*address++=*start++)!='\0');      
        return address-(len+1);      
    }     
    return NULL;     
}