- C 標準庫
- C 庫 - 首頁
- C 庫 - <assert.h>
- C 庫 - <complex.h>
- C 庫 - <ctype.h>
- C 庫 - <errno.h>
- C 庫 - <fenv.h>
- C 庫 - <float.h>
- C 庫 - <inttypes.h>
- C 庫 - <iso646.h>
- C 庫 - <limits.h>
- C 庫 - <locale.h>
- C 庫 - <math.h>
- C 庫 - <setjmp.h>
- C 庫 - <signal.h>
- C 庫 - <stdalign.h>
- C 庫 - <stdarg.h>
- C 庫 - <stdbool.h>
- C 庫 - <stddef.h>
- C 庫 - <stdio.h>
- C 庫 - <stdlib.h>
- C 庫 - <string.h>
- C 庫 - <tgmath.h>
- C 庫 - <time.h>
- C 庫 - <wctype.h>
- C 標準庫資源
- C 庫 - 快速指南
- C 庫 - 有用資源
- C 庫 - 討論
- C 程式設計資源
- C 程式設計 - 教程
- C - 有用資源
C 庫 - strncpy() 函式
C 庫函式 `strncpy()` 接受三個引數 (dest, src, n),它將 `src` 指向的字串中最多 `n` 個字元複製到 `dest`。如果 `src` 的長度小於 `n`,則 `dest` 的剩餘部分將用空位元組填充。
語法
以下是 C 庫函式 `strncpy()` 的語法:
char *strncpy(char *dest, const char *src, size_t n)
引數
此函式接受以下引數:
dest − 這是指向目標陣列的指標,內容將被複制到該陣列。
src − 這是要複製的字串。
n − 要從源複製的字元數。
返回值
此函式返回指向已複製字串的指標。
示例 1
以下是一個基本的 C 庫程式,演示了 `strncpy()` 函式的用法。
#include <stdio.h>
#include <string.h>
int main () {
char src[40];
char dest[12];
memset(dest, '\0', sizeof(dest));
strcpy(src, "This is tutorialspoint.com");
strncpy(dest, src, 10);
printf("Final copied string : %s\n", dest);
return(0);
}
輸出
執行上述程式碼後,我們將得到以下結果:
Final copied string : This is tu
示例 2
下面的示例演示了使用自定義字串複製和固定長度。
#include <stdio.h>
#include <string.h>
void customStrncpy(char* dest, const char* src, size_t n) {
size_t i;
for (i = 0; i < n && src[i] != '\0'; i++) {
dest[i] = src[i];
}
while (i < n) {
// Fill remaining characters with null terminators
dest[i] = '\0';
i++;
}
}
int main() {
char source[] = "String Copy!";
// Fixed length
char destination[15];
customStrncpy(destination, source, 10);
printf("Custom copied string: %s\n", destination);
return 0;
}
輸出
執行上述程式碼後,我們將得到以下結果:
Custom copied string: String Cop
示例 3
在這個程式中,`strncpy()` 將源字串中的固定長度子字串複製到目標字串中。
#include <stdio.h>
#include <string.h>
int main() {
char source[] = "Hello, Note!";
// Fixed length
char destination[10];
// Copy "Note!"
strncpy(destination, source + 7, 4);
printf("Copied substring: %s\n", destination);
return 0;
}
輸出
執行上述程式碼後,我們將得到以下結果:
Copied substring: Note
廣告