【C语言】字符串

自定义写string中的一些库函数

(1)strcat()——mystrcat()

void mystrcat(char *s1,char *s2)
{
    int i = 0,j = 0;
    while(s1[i] != '\0')
    {
        i++;
    }
    while(s2[j] !='\0')
    {
        s1[i] = s2[j];
        i++;
        j++;
    }
    s1[i] = '\0';   
     
}

(2)strcpy()——mystrcpy()

void mystrcpy(char s1[],char s2[])
{
    int i = 0;
    while (s2[i] != '\0')
    {
        s1[i] = s2[i];
        i++;
    }
    s1[i] = '\0';
}

(3)strcmp()——mystrcmp()

int mystrcmp(char *s1,char *s2)
{
    while(*s1 == *s2)
    {
        if(*s1 == '\0')
        {
            return 0;
        }
        s1++;
        s2++;
    }
    
    return *s1 - *s2;  //不相同则返回字符差值

(4)strlen()——mystrlen()

int mystrlen(char *s)
{
    //记录串长度,不记录\0
    int i = 0;
    while(*s != '\0')
    {
        s++;
        i++;
    }
    return i;
}

(5)strlwr()——mystrlwr()

void mystrlwr(char *s)
{
    int i = 0;
    while (s[i] != '\0')
    {
        if(s[i] >= 'A' && s[i] <= 'Z')
        {
            s[i] += 'a' - 'A';
        }
        i++;
    }
}

(6)strupr()——mystrupr()

void mystrupr(char *s)
{
    int i = 0;
    while (s[i] != '\0')
    {
        if(s[i] >= 'a' && s[i] <= 'z')
        {
            s[i] -= 'a' - 'A';
        }
        i++;
    }
}

猜你喜欢

转载自blog.csdn.net/qq_42417182/article/details/87217209