仿照str系列函数,完成自定义的mystrlen 、mystrcmp、mystrcat、mystrcpy

作业1:mystrlen函数

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

    int mystrlen(char s[])    //定义一个求字符串长度的函数
    {
        int i;
        for(i=0;s[i]!='\0';i++);    //遍历字符串直到\0结束,得出字符串长度 
        
            return i;
    }


int main(int argc, const char *argv[])
{
    char s[20]="hello shanghai";     //定义一个字符串
    int len=mystrlen(s);        //求实际长度
    
        printf("len=%d\n",len);
        
        return 0;
}

作业2、mystrcmp函数

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

    int  mystrcmp(char *p1,char *p2)
    {
        if(*p1=='\0'&&*p2=='\0')    //判断p1与p2是否相等
            return 0;
        if(*(p1)>*(p2)||*(p1)<*(p2)) //判断p1与p2的大小
                return *p1-*p2;
            if(*(p1)==*(p2))         // p1与p2相等时
                return mystrcmp(p1+1,p2+1);    //返回值为p1与p2的下一位,再次比较

    }

       
int main(int argc, const char *argv[])
{
    char s1[20];
    char s2[20];
    printf("输入第一个字符串:");
    gets (s1);
    printf("输入第二个字符串:");
    gets(s2);
    int cmp=mystrcmp(s1,s2);
    if(cmp>0)
        printf("第一个字符串大\n");
    else if (cmp<0)
        printf("第二个字符串大\n");
    else 
        printf("两个字符一样大\n");
    return 0;
}

作业3、mystrcat函数

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

    char *mystrcat(char *p,char *q)
    {
        int i=0,j=0;
        while(p[i]!='\0')
        {
            i++;            //得出p字符串长度
        }
        for(j=0;q[j]!='\0';j++)
        {
            p[i]=q[j];        //将字符串q加到字符串p之后
            i++;
        }
        p[i]=q[j];           //将'\0'加到新p结尾
        return p;
    }


int main(int argc, const char *argv[])
{
    char s1[20]="hello";
    char s2[20]="worldqw";
    mystrcat(s1,s2);             //将字符串s2加到字符串s1之后
     printf("s1=%s\n",s1);
    return 0;
}

作业4、mystrcpy函数

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

    char *mystrcpy(char *p,char *q)
    {
        int i=0,j=0;        
        for(j=0;q[j]!='\0';j++)
        {
            p[j]=q[j];     //将第二个字符串拷贝给第一个字符串
        }
        p[j]=q[j];    //将'\0'赋值到p结尾
        return p;
    }


int main(int argc, const char *argv[])
{
    char s1[20]="hello";
    char s2[20]="worldqw";       //定义两个字符串数组
    mystrcpy(s1,s2);          // 将第二个字符串拷贝给第一个数组
     printf("s1=%s\n",s1);
    return 0;
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值