1. 程式人生 > >C 標準庫 - string.h之strncpy使用

C 標準庫 - string.h之strncpy使用

填充 reat 函數 clas != count imu serve uno

strncpy

  • 把 src 所指向的字符串復制到 dest,最多復制 n 個字符。當 src 的長度小於 n 時,dest 的剩余部分將用空字節填充。
char *strncpy(char *destination, const char *source, size_t num)

Parameters

destination

  • Pointer to the destination array where the content is to be copied.
  • 指向用於存儲復制內容的目標數組。

source

  • C string to be copied.
  • 要復制的字符串。

num

  • Maximum number of characters to be copied from source.size_t is an unsigned integral type.
  • 要從源中復制的字符數。

Return Value

  • destination is returned.
  • 該函數返回最終復制的字符串。

復制 src 所指向的字符數組的至多 count 個字符(包含空終止字符,但不包含後隨空字符的任何字符)到 dest 所指向的字符數組。

  • 若在完全復制整個 src 數組前抵達 count ,則結果的字符數組不是空終止的。
  • 若在復制來自 src 的空終止字符後未抵達 count ,則寫入額外的空字符到 dest ,直至寫入總共 count 個字符。
  • 若字符數組重疊,若 dest 或 src 不是指向字符數組的指針(包含若 dest 或 src 為空指針),若 dest 所指向的數組大小小於 count ,或若 src 所指向的數組大小小於 count 且它不含空字符,則行為未定義。

Example

//
// Created by zhangrongxiang on 2017/8/24 14:36.
// Copyright (c) 2017 ZRX . All rights reserved.
//
#include <stdio.h>
#include <string.h>

int main() {
    int i = 0;
    char destination[] = "********************"; // destination串為: "********************0"
    printf("strlen(destination) -> %d
\n",strlen(destination)); //strlen(destination) -> 20 const char *source = "-----"; // source串為: "-----0" /** * C/C++中的strncpy()函數功能為將第source串的前n個字符拷貝到destination串,原型為: * 1、num<source串的長度(不包含最後的'\0'字符): * 那麽該函數將會拷貝source的前num個字符到destination串中(不會自動為destination串加上結尾的'\0'字符); * 2、num=source串的長度(包含最後的'\0'字符): * 那麽該函數將會拷貝source的全部字符到destination串中(包括source串結尾的'\0'字符); * 3、num>source串的長度(包含最後的'\0'字符): * 那麽該函數將會拷貝source的全部字符到destination串中(包括source串結尾的'\0'字符), * 並且在destination串的結尾繼續加上'\0'字符,直到拷貝的字符總個數等於num為止。 */ strncpy(destination, source, 5 ); // -----*************** // destination串為: "-----***************0" printf("%s\n",destination); // strncpy( destination, source, 6 ); // ----- // destination串為: "-----0**************0" printf("%s\n",destination); strncpy(destination, source, 10); // destination串為: "-----00000**********0" printf("-> %s\n", destination); printf("sizeof(destination)%d\n", sizeof(destination));//21 printf("--> %c\n", destination[sizeof(destination) - 2]);//* printf("--> %c\n", destination[strlen(destination) - 1]);//- for (; i < sizeof(destination); ++i) { printf("%d%c\t",i,destination[i]); } // 0- 1- 2- 3- 4- 5 6 7 8 9 10* 11* 12* 13* 14* 15* 16* 17* 18* 19* 20 } // A simple implementation of strncpy() might be: char * strncpy(char *dest, const char *src, size_t n) { size_t i; for (i = 0; i < n && src[i] != '\0'; i++) dest[i] = src[i]; for ( ; i < n; i++) dest[i] = '\0'; return dest; }

文章參考

  • http://man7.org/linux/man-pages/man3/strncpy.3.html
  • http://www.cplusplus.com/reference/cstring/strncpy/
  • http://zh.cppreference.com/w/c/string/byte/strncpy
  • http://www.runoob.com/cprogramming/c-function-strncpy.html

C 標準庫 - string.h之strncpy使用