模拟实现strncpy,strncat,strncmp

main()函数中的例子全部取于cplusplus网站

模拟实现strncat

char* Strncat(char* dest,const char* src,size_t num){    
  assert(dest != NULL);    
  assert(src != NULL);    
  unsigned int i = 0;    
  for(i = 0;i < num; i++);    
  strncpy(&dest[i],src,num);    
  return dest;    
}    

int main(){    
  char str1[20];    
  char str2[20];    
  strcpy (str1,"To be ");    
  strcpy (str2,"or not to be");    
  Strncat (str1, str2, 6);    
  puts (str1);    
  return 0;    
}    

模拟实现strncmp

int Strncmp(const char *dest, const char*src, int count)
{
	assert(dest != NULL);
	assert(src != NULL);
	while (count && *dest != '\0' && *src != '\0')
	{
		if (*dest > *src){
			return 1;
		}
		else if (*dest < *src){
			return -1;
		}
		else{
			dest++;
			src++;
			count--;
		}
	}
}
int main()
{
	char str[][5] = { "R2D2", "C3PO", "R2A6" };
	int n;
	printf("Looking for R2 astromech droids...\n");
	for (n = 0; n<3; n++)
	if (Strncmp(str[n], "R2xx", 2) == 0)
	{
		printf("found %s\n", str[n]);
	}

strncpy模拟实现

char* Strncpy(char* dest, const char* src, size_t num){    
  assert(dest != NULL);    
  assert(src != NULL);    
  int64_t i = 0;    
  for(i = 0;(unsigned)i < num;i++){    
    dest[i] = src[i];    
  }    
  dest[num] = '\0';    
  return dest;    
}    
int main(){
  char str1[]= "To be or not to be";
  char str2[40];
  char str3[40];

  /* copy to sized buffer (overflow safe): */
  Strncpy ( str2, str1, sizeof(str2)  );

  /* partial copy (only 5 chars): */
  Strncpy ( str3, str2, 7  );
  str3[7] = '\0';   /* null character manually added */

  puts (str1);
  puts (str2);
  puts (str3);
  return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值