strncpy函数的用法

来源:互联网 发布:淘宝网首页秋季女装 编辑:程序博客网 时间:2024/05/20 20:11

文章来源:http://blog.sina.com.cn/s/blog_4c4efaf6010008xu.html

利用标准库函数strncpy(),可以将一字符串的一部分拷贝到另一个字符串中。strncpy()函数有3个参数:第一个参数是目录字符串;第二个参数是源字符串;第三个参数是一个整数,代表要从源字符串拷贝到目标字符串中的字符数。以下是一个用strncpy()函数拷贝字符串的一部分的例子:    

# include <stdio. h># include <string. h>void main(void);void main (void){    char * source_str = "THIS IS THE SOURCE STRING" ;    char dest_strl[40]= {0}, dest_str2[40]= {0};    / * Use strncpy() to copy only the first 11 characters. * /    strncpy(dest_strl, source-str, 11);    printf("How about that! dest-strl is now: '%s'!!!\n", dest-strl);    / * Now, use strncpy() to copy only the last 13 characters. * /    strncpy(dest_strl, source_str + (strlen(source_str)-l3) , 13);    printf("Whoa! dest_str2 is now: '%s'!!!\n". dest_str2);}



    在上例中,第一次调用strncpy()函数时,它将源字符串的头11个字符拷贝到dest_str1中,这是一种相当直接的方法,你可能会经常用到。第二次调用strncpy()函数时,它将源字符串的最后13个字符拷贝到dest_str2中,其实现过程为:
    (1)用strlen()函数计算出source_str字符串的长度,即strlen(source_str)。
    (2)将source_str的长度减去13(13是将要拷贝的字符数),得出source_str中剩余的字符数,即pstrlen(source_str)-13。
    (3)将strlen(source_str)-13和source_str的地址相加,得出指向source_str中倒数第13个字符的地址的指针,即source_str+(strlen(source_str)-13)。这个指针就是strncpy()函数的第二个参数。
    (4)在strncpy()函数的第三个参数中指定要拷贝的字符是13。

上例的打印输出如下所示:
    How about that! dest_str1 is now:'THIS IS THE'!!!

原创粉丝点击