strnpy函数

函数原型:

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

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

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

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

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] = '\0';   /* 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变为"abcd\06789"

情形3:

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

结果:str2变为"abcd\0\0\089"


posted @ 2014-08-10 16:41  gongpixin  阅读(489)  评论(0编辑  收藏  举报