• C语言字符串处理库函数大全


    C语言中最常用标准库函数
    C++ sizeof的使用总结
    C++ Builder cstdlib 标准库函数
    相关颜色的十六进制值
    C++中几个罕见却有用的预编译和宏定义
    Windows常用快捷键

    一、string.h中字符串处理函数

    在头文件<string.h>中定义了两组字符串函数。第一组函数的名字以str开头;第二组函数的名字以mem开头。
    只有函数memmove对重叠对象间的拷贝进行了定义,而其他函数都未定义。比较类函数将其变量视为unsigned char类型的数组。

    1 strcpy

    #include <string.h>
    char *strcpy(char *str1, const char *str2);
    把字符串str2(包括'')拷贝到字符串str1当中,并返回str1。

    2 strncpy

    #include <string.h>
    char *strncpy(char *str1, const char *str2, size_t count);
    把字符串str2中最多count个字符拷贝到字符串str1中,并返回str1。如果str2中少于count个字符,那么就用''来填充,直到满足count个字符为止。

    3 strcat

    #include <string.h>
    char *strcat(char *str1, const char *str2);
    把str2(包括'')拷贝到str1的尾部(连接),并返回str1。其中终止原str1的''被str2的第一个字符覆盖。

    4 strncat

    #include <string.h>
    char *strncat(char *str1, const char *str2, size_t count);
    把str2中最多count个字符连接到str1的尾部,并以''终止str1,返回str1。其中终止原str1的''被str2的第一个字符覆盖。
    注意,最大拷贝字符数是count+1。

    5 strcmp

    #include <string.h>
    int strcmp(const char *str1, const char *str2);
    按字典顺序比较两个字符串,返回整数值的意义如下:
    小于0,str1小于str2;
    等于0,str1等于str2;
    大于0,str1大于str2;

    6 strncmp

    #include <string.h>
    int strncmp(const char *str1, const char *str2, size_t count);
    同strcmp,除了最多比较count个字符。根据比较结果返回的整数值如下:
    小于0,str1小于str2;
    等于0,str1等于str2;
    大于0,str1大于str2;

    7 strchr

    #include <string.h>
    char *strchr(const char *str, int ch);
    返回指向字符串str中字符ch第一次出现的位置的指针,如果str中不包含ch,则返回NULL。

    8 strrchr

    #include <string.h>
    char *strrchr(const char *str, int ch);
    返回指向字符串str中字符ch最后一次出现的位置的指针,如果str中不包含ch,则返回NULL。

    9 strspn

    #include <string.h>
    size_t strspn(const char *str1, const char *str2);
    返回字符串str1中由字符串str2中字符构成的第一个子串的长度。

    10 strcspn

    #include <string.h>
    size_t strcspn(const char *str1, const char *str2);
    返回字符串str1中由不在字符串str2中字符构成的第一个子串的长度。

    11 strpbrk

    #include <string.h>
    char *strpbrk(const char *str1, const char *str2);
    返回指向字符串str2中的任意字符第一次出现在字符串str1中的位置的指针;如果str1中没有与str2相同的字符,那么返回NULL。

    12 strstr

    #include <string.h>
    char *strstr(const char *str1, const char *str2);
    返回指向字符串str2第一次出现在字符串str1中的位置的指针;如果str1中不包含str2,则返回NULL。

    13 strlen

    #include <string.h>
    size_t strlen(const char *str);
    返回字符串str的长度,''不算在内。

    14 strerror

    #include <string.h>
    char *strerror(int errnum);
    返回指向与错误序号errnum对应的错误信息字符串的指针(错误信息的具体内容依赖于实现)。

    15 strtok

    #include <string.h>
    char *strtok(char *str1, const char *str2);
    在str1中搜索由str2中的分界符界定的单词。
    对strtok()的一系列调用将把字符串str1分成许多单词,这些单词以str2中的字符为分界符。第一次调用时str1非空,它搜索str1,找出由非str2中的字符组成的第一个单词,将str1中的下一个字符替换为'',并返回指向单词的指针。随后的每次strtok()调用(参数str1用NULL代替),均从前一次结束的位置之后开始,返回下一个由非str2中的字符组成的单词。当str1中没有这样的单词时返回NULL。每次调用时字符串str2可以不同。
    如:

    char *p;
    p = strtok("The summer soldier,the sunshine patriot", " ");
    printf("%s", p);
    do {
        p = strtok("", ", "); /* 此处str2是逗号和空格 */
        if (p)
            printf("|%s", p);
    } while (p);
    

    显示结果是:The | summer | soldier | the | sunshine | patriot

    16 memcpy

    #include <string.h>
    void *memcpy(void *to, const void *from, size_t count);
    把from中的count个字符拷贝到to中。并返回to。

    17 memmove

    #include <string.h>
    void *memmove(void *to, const void *from, size_t count);
    功能与memcpy类似,不同之处在于,当发生对象重叠时,函数仍能正确执行。

    18 memcmp

    #include <string.h>
    int memcmp(const void *buf1, const void *buf2, size_t count);
    比较buf1和buf2的前count个字符,返回值与strcmp的返回值相同。

    19 memchr

    #include <string.h>
    void *memchr(const void *buffer, int ch, size_t count);
    返回指向ch在buffer中第一次出现的位置指针,如果在buffer的前count个字符当中找不到匹配,则返回NULL。

    20 memset

    #include <string.h>
    void *memset(void *buf, int ch, size_t count);
    把buf中的前count个字符替换为ch,并返回buf。

    二、stdlib.h中字符串与数字相互转换处理函数

    1. 数字转化为字符串:

    ● itoa():将整型值转换为字符串。
    ● ltoa():将长整型值转换为字符串。
    ● ultoa():将无符号长整型值转换为字符串。
    ● gcvt():将浮点型数转换为字符串,取四舍五入。
    ● ecvt():将双精度浮点型值转换为字符串,转换结果中不包含十进制小数点。
    ● fcvt():指定位数为转换精度,其余同ecvt()。
    例子:

    # include <stdio.h>
    # include <stdlib.h>
    int main ()
    {
       int num_int = 435;
       double num_double = 435.10f;
       char str_int[30];
       char str_double[30];
       itoa(num_int, str_int, 10);  //把整数num_int转成字符串str_int
       gcvt(num_double, 8, str_double);  //把浮点数num_double转成字符串str_double
       printf("str_int: %s
    ", str_int);
       printf("str_double: %s
    ", str_double);
       return 0;
    }
    

    程序输出结果:
    str_int: 435
    str_double: 435.10001
    ● 代码第11行中的参数10表示按十进制类型进行转换,转换后的结果是“435”,如果按二进制类型进行转换,则结果为“1101110011”。
    ● 代码第12行中的参数8表示精确位数,这里得到的结果是“435.10001”。

    2. 字符串转化为数字

    ● atof():将字符串转换为双精度浮点型值。
    ● atoi():将字符串转换为整型值。
    ● atol():将字符串转换为长整型值。
    ● strtod():将字符串转换为双精度浮点型值,并报告不能被转换的所有剩余数字。
    ● strtol():将字符串转换为长整值,并报告不能被转换的所有剩余数字。
    ● strtoul():将字符串转换为无符号长整型值,并报告不能被转换的所有剩余数字。
    例子:

    # include <stdio.h>
    # include <stdlib.h>
    int main ()
    {
        int num_int;
        double num_double;
        char str_int[30] = "435";         //将要被转换为整型的字符串
        char str_double[30] = "436.55";  //将要被转换为浮点型的字符串
        num_int = atoi(str_int);          //转换为整型值
        num_double = atof(str_double);  //转换为浮点型值
        printf("num_int: %d
    ", num_int);
        printf("num_double: %lf
    ", num_double);
        return 0;
    }
    

    输出结果:
    num_int: 435
    num_double: 436.550000

    三. C++字符串,数字相互转换

    一.将CString转为CTime的几种方法

    CString   timestr   =   "2000年04月05日";  
      int   a,b,c   ;  
      sscanf(timestr.GetBuffer(timestr.GetLength()),"%d年%d月%d日",&a,&b,&c);  
      CTime   time(a,b,c,0,0,0);    
    

     CString   s("2001-8-29   19:06:23");  
      int   nYear,   nMonth,   nDate,   nHour,   nMin,   nSec;  
      sscanf(s,   "%d-%d-%d   %d:%d:%d",   &nYear,   &nMonth,   &nDate,   &nHour,   &nMin,   &nSec);  
      CTime   t(nYear,   nMonth,   nDate,   nHour,   nMin,   nSec);
    

    CString   timestr   =   "2000年04月05日";  
      int   year,month,day;  
      BYTE   tt[5];  
      //get   year  
      memset(tt,   0,   sizeof(tt));  
      tt[0]   =   timestr[0];  
      tt[1]   =   timestr[1];  
      tt[2]   =   timestr[2];  
      tt[3]   =   timestr[3];  
      year=   atoi((char   *)tt);  
       
      //get   month  
      memset(tt,   0,   sizeof(tt));  
      tt[0]   =   timestr[6];  
      tt[1]   =   timestr[7];  
      month   =   atoi((char   *)tt);  
       
      //get   day  
      memset(tt,   0,   sizeof(tt));  
      tt[0]   =   timestr[10];  
      tt[1]   =   timestr[11];  
     
      CTime   time(year,month,day,0,0,0);
    

    从上面来看,很明显使用sscanf()函数的优势.

    二.将CTIme转换为CString的方法:

    CTime  tmSCan = CTime::GetCurrentTime();
    CString szTime = tmScan.Format("'%Y-%m-%d %H:%M:%S'");
    

    这样得到的日期时间字符串就是以"2006-11-27 23:30:59"的格式.这是不是很方便呢?

     //取得CTime中的日期
     CString cstrDate = tmScan.Format("%Y-%m-%d");
     //取得CTime中的时间
     CString cstrTime = tmScan.Format("%H:%M-%S");
    

    sprintf还有个不错的表妹:strftime,专门用于格式化时间字符串的,用法跟她表哥很像,也是一大堆格式控制符,只是毕竟小姑娘家心细,她还要调用者指定缓冲区的最大长度,可能是为了在出现问题时可以推卸责任吧。这里举个例子:
    更多更好的sprintf()函数说明参考:《spirntf,你知道多少?》

    time_t t = time(0);
          //产生"YYYY-MM-DD hh:mm:ss"格式的字符串。
    char s[32];
    strftime(s, sizeof(s), "%Y-%m-%d %H:%M:%S", localtime(&t));
    

    sprintf在MFC中也能找到他的知音:CString::Format,strftime在MFC中自然也有她的同道:CTime::Format,这一对由于从面向对象哪里得到了赞助,用以写出的代码更觉优雅。

    三, 字符串转换为数值类型

    将字符串"20.0E6"转换为数字

    1,sscanf("20.0e5","%d",&x);
    2,atof("20.0E6");
    

    许多人用atoi(), atof() 和这个“家族”中的其它函数. 它们方便应用,但是有一个重要的缺点:
    在转换失败和转换字符串"0"时都返回0, 这样使得一致性错误检查变得几乎不可能。 为了完整性我们给出了小段代码:

    代码:

       const char* str_int = "777";
       const char* str_float = "333.3";
       int i = atoi(str_int);
       float f = atof(str_float);
    

    一个更好的办法:
    更有一点复杂, 更遗一致的办法是利用sscanf()
    代码:

       const char* str_int = "777";
       const char* str_float = "333.3";
       int i;
       float f;
       if(EOF == sscanf(str_int, "%d", &i)){
          //错误
       }
       if(EOF == sscanf(str_float, "%f", &f)){
          //错误
       }
    

    Since sscanf() takes a const char* parameter, you can directly use a CString with it:
    因为sscanf()用const char* 作为参数, 所以你可以直接用CString作参数:
    代码:

       CString str_int("777");
       if(EOF == sscanf(str_int, "%d", &i)){
          //error
       }
    

    小心格式描述符(如本例中的"%d")。 sscanf()没有办法检查格式描述符与传递变量的类型匹配与否。如果不匹配你将得到不可预期的结果。 同样注意sscanf()可以一次从字符串中提取一个或多个数值。 详细信息请查阅MSDN。

    C++ 方法
    如下的例子展示了利用标准C++类的来完成这个任务的模板函数
    代码:

    #include <string>
    #include <sstream>
    #include <iostream>
    template <class T>
    bool from_string(T &t,
                     const std::string &s,
                     std::ios_base & (*f)(std::ios_base&))
    {
       std::istringstream iss(s);
       return !(iss>>f>>t).fail();
    }
    int main()
    {
       int i;
       float f;
       // from_string()的第三个参数应为如下中的一个
       // one of std::hex, std::dec 或 std::oct
       if(from_string<int>(i, std::string("ff"), std::hex)){
          std::cout<<i<<std::endl;
       }
       else{
          std::cout<<"from_string failed"<<std::endl;
       }
       if(from_string<float>(f,
                                   std::string("123.456"),
                                   std::dec))
       {
          std::cout<<f<<std::endl;
       }
       else{
          std::cout<<"from_string failed"<<std::endl;
       }
       return 0;
    }
    

    四, int char * float and CString Covernt

    1。 int <->CString

    1. int ->CString
    int n = 1;
    CString str;
    str.Format("%d",n);
    
    1. CString->int
    CString str = "1";
    int n = atoi(str.GetBuffer(0));
    
    1. char* 与CString
      1)char*->CString
    char sz[128];
    CString str;
    str.Format("%s",sz);
    
    1. CString -> char*
    CString str;
    //int nLength = str.GetLength();
    char* sz = str.GetBuffer(0);
    
    1. float<->CString
      1)float->CString
    float f = 0.0;
    CString str;
    str.Format("%f",f);
    
    1. CString->float
    CString str = "0.0";
    float f = atof(str.GetBuffer(0));
    
  • 相关阅读:
    github not authorized eclipse 关于 代码不能提交到GitHub
    idea 导入项目后 有的项目目录结构不展开解决办法
    intellij idea 主题大全,看不惯idea 那2种主题的来这里了
    win10 系统输入法与 idea的 ctr+shift+f 快捷键冲突,解决办法
    此地址使用了一个通常用于网络浏览以外目的的端口。出于安全原因,Firefox 取消了该请求。
    关于IntelliJ IDEA有时候快捷键无效的说明
    杜恩德是谁?
    oracle如何连接别人的数据库,需要在本地添加一些配置
    2.6---找有环链表的开头结点(CC150)
    2.3---删除链表的结点,不提供头结点(CC150)
  • 原文地址:https://www.cnblogs.com/spfanlost/p/13764219.html
Copyright © 2020-2023  润新知