模拟实现strncat 主要思想:将一个字符串中的前num个字节链接到另一个字符串的后面,实现两个字符串的拼接. 将一个字符串的指针指向该字符串的末尾,将另一个的前num 个拷贝上去,最后以 ‘\0’ 结尾
//模拟实现strncat
//主要思想:将一个字符串中的前num个字节链接到另一个字符串的后面,实现两个字符串的拼接.
//将一个字符串的指针指向该字符串的末尾,将另一个的前num 个拷贝上去,最后以 ‘\0’ 结尾
#define _crt_secure_no_warnings
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
//将source中前num个字符链接到destination,最后以 '\0' 结尾
/*
char* mystrncat(char* destination, const char* source, size_t num)
{
if (destination == NULL){
return NULL;
}
if (source == NULL){
return destination;
}
char* dest = destination + strlen(destination);
for (size_t i = 0; i < num; i++){
*(dest++) = *(source++);
}
//字符串末尾以 '\0' 结尾
*dest = '\0';
return destination;
}
*/
char * mystrncat(char * dst, const char * src, size_t n)
{
char * tmp = dst;
while (*dst)
{
dst++;
}
int i;
for (i = 0; src[i] && i < n; i++)
{
dst[i] = src[i];
}
dst[i] = 0;
return tmp;
}
int main(){
char dest[1024] = "my name is ";
const char source[] = "wangJiao!";
if (dest != NULL&&*source != '\0'){
//printf("strncat=%s\n",strncat(dest, source, strlen(source)));
printf("%s\n", mystrncat(dest, source, strlen(source)));
}
system("pause");
return 0;
}