【C语言】模拟实现strlen,strcpy,strcat,srcmp

本文介绍了如何使用C语言手动实现strlen、strcpy、strcat和strcmp四个字符串处理函数,详细展示了实现过程及运行结果。

模拟实现strlen,strcpy,strcat,srcmp

一:模拟实现strlen
#include<stdio.h>
#include<stdlib.h>
#include<assert.h>
int my_strlen(char* str)
{
assert(str != NULL);
int count = 0;
while (*str != '\0')
{
  str++;
  count++;
}
return count;
}
int main()
{
char arr[] = "abc";
int ret=my_strlen(arr);
printf("%d\n", ret);
system("pause");
return 0;
}

运行结果如下
在这里插入图片描述

二:模拟实现strcpy
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<assert.h>
char* my_strcpy( char* pdest, const char* psre)
{
char* start = pdest;
assert(pdest != NULL);
assert(psre != NULL);
while (*pdest = *psre)
{
  pdest++;
  psre++;
}
return start;
}
int main()
{
char arr1[] = "hello word";
char arr2[20] = "0";
my_strcpy(arr2, arr1);
printf("%s\n",my_strcpy(arr2,arr1));
system("pause");
return 0;
}

运行结果如下:
在这里插入图片描述

三:模拟实现strcat
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<assert.h>
char* my_strcat(char* pdest, char* psrc)
{
char* start = pdest;
assert(pdest != NULL);
assert(psrc != NULL);
while (*pdest)
{
  pdest++;
}
while ( *psrc);
{
*pdest++ = *psrc++;
}
return start;
}
int main()
{
char arr1[20] = "abc";
char arr2[] = "def";
my_strcat(arr1, arr2);
printf("%s\n", my_strcat(arr1, arr2));
system("pause");
return 0;
}

运行结果如下:
在这里插入图片描述

四:模拟实现strcmp
#include<stdio.h>
#include<stdlib.h>
#include<assert.h>
#include<string.h>
int my_strcmp(char* arr1, char* arr2)
{
 assert(arr1 != NULL);
 assert(arr2 != NULL);
 int i = 0;
 int len;
 int len1 = strlen(arr1);
 int len2 = strlen(arr2);
 if (len1 > len2)
 {
  len = len1;
 }
 else
 {
  len = len2;
 }
 for (i = 0;i < len;i++)
 {
  if (arr1[i] == arr2[i] && arr1[i] != '\0')
  {
   continue;
  }
  if (arr1[i] < arr2[i])
  {
   return -1;
  }
  if ((arr1[i] == '\0') && (arr2[i] == '\0'))
  {
   return 0;
  }
  else
  {
   break;
  }
 }
 return 1;
}
int main()
{
 char arr1[] = "abc";
 char arr2[] = "defg";
 my_strcmp(arr1, arr2);
 printf("%d\n", my_strcmp(arr1, arr2));
 system("pause");
 return 0; 
}

运行结果如下:
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值