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'!!!

  • 相关阅读:
    uva11916 Emoogle Grid (BSGS)
    2016vijos 1-2 股神小L(堆)
    bzoj千题计划311:bzoj5017: [Snoi2017]炸弹(线段树优化tarjan构图)
    Oracle Profile 使用详解--zhuanzai
    通过srvctl add命令添加database信息到srvctl管理器-转
    Oracle Dataguard Standby Redo Log的两个实验
    MySQL数据的主从复制、半同步复制和主主复制详解-转
    解决oralce 11g dg搭建报错:ORA-16664、ORA-16714、ORA-16810问题--转
    oracle分布式事务总结-转载
    日志挖掘Logmnr
  • 原文地址:https://www.cnblogs.com/zhwl/p/2762487.html
Copyright © 2011-2022 走看看