zoukankan      html  css  js  c++  java
  • [C/C++] 字符串处理函数 strstr 与 strncpy

    strstr()
    函数原型:extern char *strstr(char *str1, char *str2);
    功能:找出str2字符串在str1字符串中第一次出现的位置(不包括str2的串结束符)。
    返回值:返回该位置的指针,如找不到,返回空指针。
    /* strstr example */
    #include <stdio.h>
    #include <string.h>
    
    int main() {
      char str[] = "This is a simple string";
      char *pch;
      pch = strstr (str, "simple");
      puts(pch);
      strncpy (pch, "123sample", 6);
      puts(pch);
      puts (str);
      return 0;
    }
    /*
    Output
    simple string
    123sam string
    This is a 123sam string
    */

    strncpy  字符串复制

    原型:char * strncpy(char *dest, char *src, size_t n);
    功能:将字符串src中最多n个字符复制到字符数组dest中(它并不像strcpy一样只有遇到NULL才停止复制,而是多了一个条件停止,就是说如果复制到第n个字符还未遇到NULL,也一样停止),返回指向dest的指针。
    /* 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;
    }
    /*
    To be or not to be
    To be or not to be
    To be
    */

  • 相关阅读:
    从贫困生到创业者
    招聘会技巧:应聘外企的英语提问清单
    智能客户端(SmartClient)
    GOOGLE 技巧
    值得珍藏
    三个大学生开软件公司 毕业前挣300万
    卡车运输业中的无线技术
    莫扎特金色的童年和少年
    开放源码 ERP
    人才招聘站点大全
  • 原文地址:https://www.cnblogs.com/robbychan/p/3787069.html
Copyright © 2011-2022 走看看