今日份学习日常(8)

作业

1> 自定义函数(my_strlen)实现strlen函数的功能

2> 自定义函数(my_strcpy)实现strcpy函数的功能

3> 自定义函数(my_strcmp)实现strcmo函数的功能

4> 自定义函数(my_strcat)实现strcat函数的功能

4> 自定义函数(my_strstr)实现求src字符串中是否包含子串dest字符串

程序代码:

#include<stdio.h>
#include<string.h>

//第一题
//strlen
size_t  my_strlen(const char *s)
{
    size_t len = 0;
    while (*s++)
    {
        len ++;             //如果字符部位'\0'则字符个数自增
    }
    return len;
}

//strcmp
int my_strcmp(const char *s1,const char *s2)
{
    int res = 0;//记录对应位置上两个字符的差值

    while (*s1 ++ == *s2++ && *s1 != '\0'  && *s2 != '\0')
    {
        //求循环后,对应两个字符串的差值
        res = *s1 - *s2;
    }

    return res;
}

//strcpy
char *my_strcpy(char *dest,const char *src)
{
    char *cp = dest;

    while (*cp++ = *src++)
    {
        return dest;
    }
}

//strcat
char *my_strcat(char *dest,const char *src)
{
    my_strcpy(dest + my_strlen(dest),src);

    return dest;
}

//自定义strstr实现求src字符串是否包含子串dest字符串
char *my_strstr(const char *haystack,const char *needle)
{
    //判断子串是否为空
    if (!*needle)
    {
        return (char *)haystack;
    }
    
    //程序执行至此,表示子串不为空
    for (char *h= haystack; *h; h++)//遍历主串
    {
        char *temp_h = (char *)h;               //记录主串当前字符
        char *temp_n = (char *)needle;          //记录子串当前的字符

        //遍历子串
        while (*temp_h && *temp_n && *temp_h++ == *temp_n++)

        //循环结束后
        if (!*temp_n )
        {
            //说明匹配成功,返回主串中第一个出现的位置
            return h;
        }
    }

    //说明主串遍历结束之后也没有匹配到子串
    return NULL;
}

int main(int argc, char const *argv[])
{
    char s1[20] = "hello woeld";
    char s2[] = "I love China";

    printf("len of s1 = %ld\n",my_strlen(s1));

    if (my_strcmp(s1,s2) > 0)
    {
        printf("%s大\n",s1);
    }else if(my_strcmp(s1,s2) < 0)
    {
        printf("%s小\n",s1);
    }else
    {
        printf("一样大\n");
    }
    
    //验证strcpy
    my_strcpy(s1,s2);
    printf("s1 = %s,s2 = %s\n",s1,s2);
    
    //验证strstr
    char *ptr = strstr(s1,"love")
    if (ptr)
    {
        printf("success: %s\n",ptr);
    }else
    {
        printf("error\n");
    }

    //验证strcat
    my_strcat(s1,"and you!!!")
    printf("s1 = %s,s2 = %s\n",s1,s2);
    
    return 0;
}


运行结果:

  • 8
    点赞
  • 17
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值