http://www.cplusplus.com/reference/string/string/
初始化
string a = "hello" 或 a("hello");
string b = a;
string c(2, 'c'); c = "cc",重复2次'c'字符
string d("hello", 3); d = "hel",拷贝前3个字符
string e(a, 2); e = "llo",将a字符串第2个位置开始拷贝完
string f(a,1,3); f = "ell", 从a字符串第1个位置开始拷贝3个字符
长度
a.size() 或 a.length()
判空
a.empty()
搜索
搜索以及其他的string操作是大小写敏感的
string::size_type string的下标类型,一个无符号整数
string::npos 初始化为-1,表示未找到
string::size_type pos = a.find(args); 从左开始搜索第一次出现的位置,找到返回下标,否则返回npos
a.rfind(args); 从右开始搜索第一次出现的位置
args:
c, pos : 从s中位置pos开始查找字符c。pos默认为0
s2,pos : 从s中位置pos开始查找字符串s2。pos默认为0
cp,pos : 从s中位置pos开始查找指针cp指向的以空字符结尾的c风格字符串。pos默认0
cp,pos,n:从s中位置pos开始查找指针cp指向的数组的前n个字符
find原型
//string (1)
size_type find (const basic_string& str, size_type pos = 0) const noexcept;
//c-string (2)
size_type find (const charT* s, size_type pos = 0) const;
//buffer (3)
size_type find (const charT* s, size_type pos, size_type n) const;
//character (4)
size_type find (charT c, size_type pos = 0) const noexcept;
子串拷贝
string substr(size_t pos = 0, size_t len = npos) const;
string a = b.substr(); 完整拷贝
string a = b.substr(1); 从下标位置为1开始拷贝
string a = b.substr(1, 3); 从下标位置为1开始拷贝长度为3的字符串
比较
==、!=、>、>=、<、<=
compare
string (1) | |
---|---|
substrings (2) | |
c-string (3) | |
buffer (4) | |
拼接
+=、+
遍历
下标
for (string::size_type i = 0; i < a.length(); i++) {
a[i]
}
迭代器
string::iterator itor = a.begin()
for (; itor != a.end(); itor++) {
}
添加
string (1) | |
---|---|
substrings (2) | |
c-string (3) | |
buffer (4) | |
删除
sequence (1) | |
---|---|
character (2) | |
range (3) | |