zoukankan      html  css  js  c++  java
  • C++中关于string类的一些API总结

    参考资料:https://www.cnblogs.com/X-Do-Better/p/8628492.html

         https://blog.csdn.net/iot_change/article/details/8496977

    一、前言

      对于C++中的string类,需要使用的话,需要包含头文件<string>。string类在C++中属于一个模板类,位于命名空间namespace中,使用的时候需要加上下一语句。

    1 using namespace std;

    二、自身特性方面的API

      1、int capacity()

      功能描述:返回当前容量【即string中在不需要增加内存的情况下还可存放的元素个数】。

      2、int max_size()

      功能描述:返回string对象中可存放的最大字符串的长度。

      3、int size()

      功能描述:返回当前字符串的大小

      4、int length()

      功能描述:返回当前字符串的长度

      5、bool empty()

      功能描述:判断当前字符串是否为空

      6、void resize(int len, char c)

      功能描述:把字符串当前大小设置为len,多去少补,字符c填充不足的部分

    三、关于查找方面的API

      1、size_type find ( const basic_string &str, size_type index )

      功能介绍:返回str在字符串中第一次出现的位置,从index开始查找,如果查找失败,则返回string::npos。

      类似的API还有以下几个。

      size_type find( const char *str, size_type index, size_type length ):返回str在字符串中第一次出现的位置(从index开始查找,长度为length),如果没找到就返回string::npos。

      size_type find( char ch, size_type index ):返回字符ch在字符串中第一次出现的位置(从index开始查找),如果没找到就返回string::npos。

      以上的查找功能都是按照从前往后的顺序进行查找,如果想要按照从后往前的顺序进行查找的话,可以用"rfind"语句。

      2、size_type find_first_of ( const string& str, size_type  pos = 0 )

       功能介绍:返回str中任意字符在字符串中第一次出现的位置,从位置0开始查找。

       类似功能的函数有以下几个。

       size_type find_first_of ( const char* s, size_type pos, size_t n )

       size_type find_first_of ( const char* s, size_type pos = 0 )

       size_type find_first_of ( char c, size_type pos = 0 )

      3、find_first_not_of

       功能与find_first_of()函数的功能正好相反。

      4、find_last_of

       与find_first_of()函数相比而言,其不同的地方在于:find_last_of()是找出最后一个相同的位置。

      5、find_last_not_of

       与find_last_of()功能函数正好相反。

    四、其他方面的函数

      1、string &insert(int p,const string &s)

      功能介绍:在p位置插入字符串s

      2、string &replace(int p, int n,const char *s)

      功能介绍:删除从p开始的n个字符,然后在p处插入字符串s

      3、string &erase(int p, int n)

      功能介绍:删除p开始的n个字符,返回修改后的字符串

      4、string substr(int pos, int n ) 

      功能介绍:返回pos开始的n个字符组成的字符串

      5、void swap(string &s2)

      功能介绍:交换当前字符串与s2的值

      6、string &append(const char *s)

      功能介绍:把字符串s连接到当前字符串结尾

      7、void push_back(char c)

      功能介绍:当前字符串尾部加一个字符c

      8、const char *data()/

      功能介绍:返回一个非null终止的c字符数组,data():与c_str()类似,用于string转const char*其中它返回的数组是不以空字符终止。

      9、const char *c_str()  

      返回一个以null终止的c字符串,即c_str()函数返回一个指向正规C字符串的指针, 内容与本string串相同,用于string转const char*

  • 相关阅读:
    linux系统日志使用
    C# progressbar 用法
    python 新时代
    linux 常用命令 集锦
    c# DirectoryInfo类 详解
    哈佛(转)
    寒门难再出贵子
    排序算法
    JavaScript弹出框
    js中innerHTML与innerText的用法与区别
  • 原文地址:https://www.cnblogs.com/wyt123/p/10711326.html
Copyright © 2011-2022 走看看