• strnpy函数


    函数原型:

    char * strncpy ( char * destination, const char * source, size_t num );

    功能:从字符串source中复制 num个字符到字符串destination中,返回指向字符串destination的指针。

    使用注意:destination串要保证能够容得下复制的内容,即destination的长度要大于num。

    当num大于source的长度的时候,会在后面补。

    Example

    <span style="font-size:12px;">/* strncpy example */
    #include <stdio.h>
    #include <string.h>
    
    int main ()
    {
      char str1[]= "To be or not to be";
      char str2[40];
      char str3[40];
    
      /* copy to sized buffer (overflow safe): */
      strncpy ( str2, str1, sizeof(str2) );
    
      /* partial copy (only 5 chars): */
      strncpy ( str3, str2, 5 );
      str3[5] = '';   /* null character manually added */
    
      puts (str1);
      puts (str2);
      puts (str3);
    
      return 0;
    }</span>

    Output:
    
    To be or not to be
    To be or not to be
    To be 
    


    使用时的三种情形:

        char *str1="abcd";//长度为5
        char str2[]="123456789";

    情形1:

        strncpy(str2,str1,3);

    从str1中复制3个字符到str2

    结果:str2变为"abc456789"

    情形2:

        strncpy(str2,str1,5);
    从str1中复制5个字符到str2,此时相当于strcpy(str2,str1);

    结果:str2变为"abcd6789"

    情形3:

        strncpy(str2,str1,7);
    从str1复制7个字符到str2(由于7大于str1的长度5,会在后面补2个)

    结果:str2变为"abcd89"


  • 相关阅读:
    构建之法阶段小记七
    构建之法阶段小记六
    构建之法阶段小记五
    构建之法阶段小记四
    构建之法阶段小记三
    短学期知识总结(二)
    短学期知识总结(一)
    《构建之法》第八章自习感想与知识点
    第15组构建之法团队心得
    《构建之法》第七章自习感想与知识点
  • 原文地址:https://www.cnblogs.com/gongpixin/p/4477419.html
Copyright © 2020-2023  润新知