zoukankan      html  css  js  c++  java
  • strncpy函数的用法

    利用标准库函数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'!!!

  • 相关阅读:
    非循环单链表节点的操作
    链表每一个节点的数据类型该如何表示
    链表的定义、确定一个链表需要几个参数?
    typedef的用法
    连续存储数组的算法(包含数组倒置、冒泡排序……)
    跨函数使用内存案例
    malloc()动态分配内存概述
    结构体
    指针和数组
    C#基础知识之dnSpy反编译
  • 原文地址:https://www.cnblogs.com/zhwl/p/2762487.html
Copyright © 2011-2022 走看看