bilibiliclass51_C語言_strncpy 指定個數的字串拷貝-函式詳解
阿新 • • 發佈:2020-12-24
技術標籤:C語言_嗶哩嗶哩課堂筆記
strncpy
指定個數的字串拷貝
庫函式內的宣告
char * strncpy ( char * destination, const char * source, size_t num );
簡單例子
#define _CRT_SECURE_NO_WARNINGS #include<stdio.h> #include<string.h> int main() { char arr1[10] = "abcdefgh"; char arr2[] = "bit"; strncpy(arr1, arr2, 6); printf("%s", arr1); return 0; } //記憶體中arr1裡面是bit\0\0\0gh\0 //結果:bit
使用:
1.拷貝num個字元從源字串到目標空間。
2.如果源字串的長度小於num,則拷貝完源字串之後,在目標的後邊追加\0,直到num個。
my_strncpy實現方法
#define _CRT_SECURE_NO_WARNINGS #include<stdio.h> #include<assert.h> char* my_strncpy(char* dest, const char* source, int count) { assert(dest != NULL); assert(source != NULL); char* ret = dest; while (count && (* dest++ = *source++)) { count--; } if (count) { while (--count) { *dest++ = '\0'; } } return ret; } int main() { char arr1[10] = "abcdefgh"; char arr2[] = "bit"; my_strncpy(arr1, arr2, 6); printf("%s", arr1); return 0; }