strncpy
char* strncpy(char* destination, const char* source, size_t num);
1.拷贝num个字符从源字符串到目的空间 2.如果源字符串的长度小于mun,则拷贝完源字符串之后,在目标的后面加0,直到num个。
#include<stdio.h>
int main() {
char arr1[10] = "abcdef";
char arr2[] = "hello world";
strncpy(arr1, arr2, 4);
printf("%s\n", arr1);
getchar();
return 0;
}
拷贝后 可见,没有将’\0’拷贝过来 当拷贝的源字符串长度小于参数时,后面补’\0’
#include<stdio.h>
int main() {
char arr1[10] = "abcdefghi";
char arr2[] = "hello";
strncpy(arr1, arr2, 9);
printf("%s\n", arr1);
getchar();
return 0;
}
拷贝后
strncpy模拟实现
#include<stdio.h>
char* my_strncpy(char* dest, const char* src, size_t num) {
char* dest1 = dest;
assert(dest && src);
while ((num)&&(*dest++ = *src++)) {
num--;
}
while((*src == '\0')&&(num)) {
*dest++ = '\0';
num--;
}
return dest1;
}
int main() {
char arr1[10] = "abcdefghi";
char arr2[] = "hello";
my_strncpy(arr1, arr2, 4);
printf("%s\n", arr1);
getchar();
return 0;
}
|