C语言--实现strncat,strncmp函数

本文详细介绍了如何实现strncat和strncmp两个字符串操作函数。strncat用于安全地将一个字符串的前n个字符拼接到另一个字符串的末尾,并确保目标字符串有足够的空间。strncmp则用于比较两个字符串的前n个字符,返回它们之间的相对大小,适用于精确控制字符串比较的场景。

实现strncat,strncmp函数

1.strncat:拼接n个字符,要是第二个字符串长度小于n,那就拼接完直接在后边加\0。同时还要保证第一个字符串长度足够+n。

char* my_Strncat(char* destination, const char* source, size_t num) {
 if (destination == NULL || source == NULL) {
  return NULL;
 }
 int cur = 0;
 while (destination[cur] != '\0') {
  cur++;
 }
 size_t i = 0;
 while ( i < num && source!='\0') {
  destination[cur + i] = source[i];
  i++;
 }
 destination[cur + i] = '\0';
 return destination;
}

2.strncmp:字符串比较函数,比较n个字符。str1<str2返回-1,否则返回1,相等返回0。

int my_Strncmp(const char* str1, const char* str2, size_t num) {
 assert(str1 != NULL && str2 != NULL);
 while (*str1 != '\0' && *str2 != '\0'&& 1 < num) {
  if (*str1 > *str2) {
   return 1;
  }
  else if (*str1 < *str2) {
   return -1;
  }
  else {
   str1++;
   str2++;
   num--;
  }
 }//出while循环代表起码有一个字符串遇到‘\0’了
 if (*str1 > * str2) {
  return 1;
 }
 else if (*str1 < *str2) {
  return -1;
 }
 else {
  return 0;
 }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值