C语言实现mystrcpy等函数

本文深入探讨了C语言中常见的字符串操作函数,包括字符串复制(mystrcpy)、比较(mystrcmp)、长度计算(mystrlen)和连接(mystrcat)。通过代码示例详细解析了这些函数的实现原理和使用方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 mystrcpy

#include <stdio.h>
#include <stdlib.h>
 
char *mystrcpy(char *ptr, const char *str)
{
    char *tmp = ptr; 
 
    while((*ptr++ = *str++) != '\n')
    {
        continue;
    }
    return tmp;
}
 
int main()
{
    char *str = "hello world";
    char *ptr;
    ptr = (char *)malloc(sizeof(char) * 1024);
 
    mystrcpy(ptr, str);
 
    printf("%s\n", ptr);
 
    return 0;
}

mystrcmp

#include <stdio.h>
#include <stdlib.h>
 
int mystrcmp(char *str, char *ptr)
{
    int i = 0;
    while (*(str + i) != '\0' && *(ptr + i) != '\0')
    {
         if(*str > *ptr)
        {
            return 1;
        }
        else if(*str < *ptr)
        {
            return -1;
        }
        i++;
    }
 
    if(*str != '\0')
    {
        return 1;
    }
     if(*ptr != '\0')
     {
         return -1;
     }
 
     return 0;
}
 
int main()
{
    int i;
    char *str, *ptr;
    str = (char *)malloc(sizeof(char)*64);
    ptr = (char *)malloc(sizeof(char)*64);
 
    printf("please input two strings:\n");
    scanf("%s%s", str, ptr);
 
   i = mystrcmp(str, ptr);
 
   if(i == 0)
   {
       printf("%s = %s", str, ptr);
   }
 
   if(i == 1)
   {
       printf("%s > %s", str, ptr);
   }
 
   if(i == -1)
   {
       printf("%s < %s", str, ptr);
   }
    return 0;
}

mystrlen

#include <stdio.h>
#include <stdlib.h>
 
void mystrlen(char *ptr)
{
    int i = 0;
    while(*(ptr + i) != '\0')// while(*ptr++ != '\0')
    {
        i++;
    }
    printf("%d\n", i);
 
}
 
int main()
{
    char *str;
    str = (char *)malloc(sizeof(char)* 64);
 
    printf("please input a string:\n");
    scanf("%s", str);
 
    mystrlen(str);
 
    return 0;
}

mystrcat

#include <stdio.h>
 
char *mystrcat(char *dest,const char *src)
{
	char *p;
	p = dest;
	while(*dest)
		dest++;
	while(*src)
	{
		*dest++ = *src++;
	}
 
	*dest = '\0';
 
	return p;
}
 
int main()
{	
	char str1[] = "hello";
	char str2[] = "world";
	mystrcat(str1,str2);
 
	printf("str1 = %s\n",str1);
 
	return 0;
 
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值