转载于:https://blog.csdn.net/lsh_2013/article/details/46728993
包含于头文件:
#include<string>
String类的构造函数如下:
string s; //生成一个空字符串s
string s(str) //拷贝构造函数生成str的复制品
string s(str,index) //将字符串str内“始于位置index”的部分当作字符串的初值
string s(str,index, n) //将字符串str内“始于index且长度顶多n”的部分作为字符串的初
string s(cstr) //将C字符串作为s的初值
string s(chars,chars_len) //将C字符串前chars_len个字符作为字符串s的初值。
string s(n,c) //生成一个字符串,包含n个c字符
string s(str.begin(),str.end()) //以区间begin():end() (不包含end())内的字符作为字符串s的初值
String类常用的操作函数
之后会对相关函数进行讲解,如果不想将下面操作函数全部看完,大伙可以找自己感兴趣的函数看。
=,assign() //赋以新值
swap() //交换两个字符串的内容
3)+=,append(),push_back() //在尾部添加字符
insert() //插入字符
erase() //删除字符
clear() //删除全部字符
replace() //替换字符
9)==,!=,<,<=,>,>=,compare() //比较字符串
10)size(),length() //返回字符数量
max_size() //返回字符的可能最大个数
empty() //判断字符串是否为空
capacity() //返回重新分配之前的字符容量
reserve() //保留一定量内存以容纳一定数量的字符
[ ], at() //存取单一字符
16)>>,getline() //从stream读取某值
<< //将谋值写入stream
copy() //将某值赋值为一个C_string
c_str() //将内容以C_string返回
data() //将内容以字符数组形式返回
substr() //返回某个子字符串
22)查找函数
23)begin() end() //提供类似STL的迭代器支持
rbegin() rend() //逆向迭代器
get_allocator() //返回配置器
字符的删除
1)iterator erase(iterator p);//删除字符串中p所指的字符
2)iterator erase(iterator first, iterator last);//删除字符串中迭代器
区间[first,last)上所有字符
3)string& erase(size_t pos = 0, size_t len = npos);//删除字符串中从索引
位置pos开始的len个字符
4)void clear();//删除字符串中所有字符
字符的替换
1)string& replace(size_t pos, size_t n, const char *s);//将当前字符串
从pos索引开始的n个字符,替换成字符串s
2)string& replace(size_t pos, size_t n, size_t n1, char c); //将当前字符串
从pos索引开始的n个字符,替换成n1个字符c
3)string& replace(iterator i1, iterator i2, const char* s);//将当前字符串
[i1,i2)区间中的字符串替换为字符串s
字符串的比较
1)int compare (conststring& str) const;//将当前字符串与字符串str比较,
相等返回0,大于str返回1,小于str返回-1
2)int compare (size_tpos, size_t len, const char* s) const; //将当前字符串从
Pos索引位置开始的len个字符构成的字符串与字符串s比较,
相等返回0,大于str返回1,小于str返回-1
3)int compare (constchar* s) const; //直接将当前字符串与字符串s比较,
相等返回0
字符的搜索
相关函数较多,下面列举几个常用的:
1)size_t find (constchar* s, size_t pos = 0) const;
//在当前字符串的pos索引位置开始,查找子串s,返回找到的位置索引,
-1表示查找不到子串
2)size_t find (charc, size_t pos = 0) const;
//在当前字符串的pos索引位置开始,查找字符c,返回找到的位置索引,
-1表示查找不到字符
3)size_t rfind (constchar* s, size_t pos = npos) const;
//在当前字符串的pos索引位置开始,反向查找子串s,返回找到的位置索引,
-1表示查找不到子串
4)size_t rfind (charc, size_t pos = npos) const;
//在当前字符串的pos索引位置开始,反向查找字符c,返回找到的位置索引,
-1表示查找不到字符
5)size_tfind_first_of (const char* s, size_t pos = 0) const;
//在当前字符串的pos索引位置开始,查找子串s的字符,返回找到的位置索引,
-1表示查找不到字符
6)size_tfind_first_not_of (const char* s, size_t pos = 0) const;
//在当前字符串的pos索引位置开始,查找第一个不位于子串s的字符,
返回找到的位置索引,-1表示查找不到字符
7)size_t find_last_of(const char* s, size_t pos = npos) const;
//在当前字符串的pos索引位置开始,查找最后一个位于子串s的字符,返回找到的位置索引,-1表示查找不到字符
8)size_tfind_last_not_of (const char* s, size_t pos = npos) const;
//在当前字符串的pos索引位置开始,查找最后一个不位于子串s的字符,返回找到的位置索引,-1表示查找不到子串