strlen strcmp strcpy strcat strchr strstr 基础实现

来源:互联网 发布:pc短信群发软件 编辑:程序博客网 时间:2024/05/19 21:59
#include <stdio.h>
#include <assert.h>

int mystrlen(char *string)
{
    int i = 0;

    while (string[i] != '\0')
        i++;

    return i;
}

int mystrcmp(const char *string1, const char *string2)
{
    int len_string1, len_string2;
    int len_max, i = 0;

    assert(string1 != NULL && string2 != NULL);

    len_string1 = mystrlen(string1);
    len_string2 = mystrlen(string2);
    len_max = (len_string1 > len_string2 ? len_string1 : len_string2);
    
    while ( i < len_max )
    {
        if (string1[i] > string2[i])
            return 1;
        else if (string1[i] < string2[i])
            return -1;
        else
            i++;
    }
    return 0;
}

char *mystrcpy(char *dst, const char *src)
{
    int len_src, i;

    assert(dst != NULL && src != NULL);
    
    len_src = mystrlen(src);

    for (i=0; i<=len_src; i++)                // '\0' 包括在内
        dst[i] = src[i];
    
    return dst;
}

/*char *mystrcat( char *dst, const char *src )
{
    int len_dst, len_src;
    int i ;

    assert(dst != NULL && src != NULL);
    
    len_dst = mystrlen(dst);
    len_src = mystrlen(src);

    for (i=0; i<=len_src; i++)                // '\0' 包括在内
        dst[len_dst + i] = src[i];

    return dst;    
}*/

char *mystrcat( char *strDestination, const char *strSource )
{
    
    int i = 0;
    int len_strDestination;
    int len_strSource;
    
    assert((strDestination!=NULL)&&(strSource!=NULL));
    
    len_strDestination = mystrlen(strDestination);
    len_strSource = mystrlen(strSource);                    //计算长度
    
    for (i=0;i<=len_strSource;i++)
    {
        strDestination[len_strDestination+i]=strSource[i];  //"fdggf"  "yyyy"
    }
    return strDestination;
    
}

char *mystrchr(const char *string, char c)
{
    int len_string, i = 0;

    assert(string != NULL);

    len_string = mystrlen(string);

    while (i < len_string)
    {
        if (string[i] == c)
            return (string + i);
        else
            i++;
    }

    return NULL;

}

char *mystrstr(const char *str1, const char *str2)
{
    int i, j;
    assert(str1 != NULL && str2 != NULL);
    for (i=0; *(str1 + i) != 0;)
    {
        for (j=0; *(str2 + j) != 0;)
        {
            if ( *(str1+i) == *(str2+j))
            {
                i++;
                j++;
                if ( *(str2 + j) == 0)
                    return str1 + i - j;
            }
            else
                i =  i - j + 1;
        }
    }

    return NULL;
}
原创粉丝点击