C語言 strncpy


C語言 strncpy

#include <string.h>
char *strncpy(char *dest, const char *src, size_t n);

功能:把src指向字符串的前n個字符復制到dest所指向的空間中,是否拷貝結束符看指定的長度是否包含'\0'。
參數:

  • dest:目的字符串首地址
  • src:源字符首地址
  • n:指定需要拷貝字符串個數

返回值:

  • 成功:返回dest字符串的首地址
  • 失敗:NULL

案例

#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <math.h>
#include <time.h>

int main(void)
{
    char ch[] = "hello world";

    // 字符串有限拷貝需要先初始化
    char str[100] = {0};

    // 字符串有限拷貝
    strncpy(str, ch, 5);

    printf("%s\n", str);

    return 0;
}
strncpy 使用案例:使用函數
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <math.h>
#include <time.h>

void my_strncpy(char* dest, const char* src,size_t n)
{
    while ((*dest++ = *src++) && --n);
}


int main(void)
{
    char ch[] = "hello world";

    // 字符串有限拷貝需要先初始化
    char str[100] = {0};
    my_strncpy(str, ch, 5);

    printf("%s\n", str);

    return 0;
}
strncpy 使用案例:創建函數

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM