
拷贝num个字符从源字符串到目标空间。
如果源字符串的长度小于num,则拷贝完源字符串之后,在目标的后边追加0,直到num个
strncpy与strcpy的作用是一样的,区别在于strncpy指定了复制字符的个数。
这里多了个参数num,指定的复制字符个数,就得考虑两种情况:
1.当 源字符串长度大于num时,正常复制到num结束。
2.当源字符串长度小于num时,就得在后面追加剩余个数的‘\0’。
- #define _CRT_SECURE_NO_WARNINGS 1
- #include<stdio.h>
- #include<string.h>
- #include<assert.h>
- //模拟实现strncpy
- char* my_strncpy(char* dest, char* src, size_t num)
- {
- char* ret = dest;
- assert(src);
- assert(dest);
- while (num&&(*dest++=*src++))//当*src=='\0'时会跳出循环
- {
- num--;
- }
- if (num)//经历上层循环后,剩余个数继续遍历加空字符
- {
- while (num--)
- {
- (*dest++) = '\0';
- }
- }
- return ret;
-
- }
-
- int main()
- {
- char str1[] = "abcdefghij";
- char str2[] = "aaaa";
- my_strncpy(str1+2, str2, 5);
- printf("%s\n", str1);
- return 0;
- }