string类的基本介绍
string是表示字符序列的字符串类;
string的接口与常规容器的接口基本相同,再添加了一些专门用来操作string的常规操作;
string在底层实际是basic_string模板类的别名,typedef basic_string<char, char_straits, allocator> tring;
不能操作多字节或者变长字符序列;
因为string实际上在stl之前就存在了,只有为了规范统一,就又加了一些东西,导致它有点冗余复杂了。
string类的常用接口
string类的构造函数
int main() { string str0("hello world"); string str1; string str2(str0); string str3(str0, 2, 5); string str4("A character sequence"); string str5("Another charater sequence", 12); string str6a(10, 'x'); string str6b(10, 120); string str7(str0.begin(), str0.begin() + 7); cout << "str1:" << str1 << endl; cout << "str2:" << str2 << endl; cout << "str3:" << str3 << endl; cout << "str4:" << str4 << endl; cout << "str5:" << str5 << endl; cout << "str6a:" << str6a << endl; cout << "str6b:" << str6b << endl; cout << "str7:" << str7 << endl; return 0; }
string类对象的访问及遍历
int main() { string str("hello world"); for (string::iterator it = str.begin(); it != str.end(); ++it) { cout << *it; } cout << endl; for (string::reverse_iterator rit = str.rbegin(); rit != str.rend(); ++rit) { cout << *rit; } cout << endl; cout << str[1] << endl; return 0; }
string类对象的容量操作
size()与length()方法底层实现原理完全相同,引入size()的原因是为了与其他容器的接口保持一直,一般情况下基本都是用size();
clear()只是将string中有效字符清空,不改变底层空间大小;
resize(size_t n)与resize(size_t n, char c)都是将字符串中有效字符的个数改变到n个,不同的是党字符个数增加时,resize(n)用0来填充多出的元素空间,resize(size_t n,char c)用字符c来填充多出来的元素空间。
reserve(size_t res_arg = 0),为string预留空间,不改变有效元素个数,当reserve的参数小于string的底层空间总大小时,reserver不会改变容量大小。
// size与length int main() { string str("hello world"); cout << "size:" << str.size() << endl; cout << "length:" << str.length() << endl; cout << "capacity:" << str.capacity() << endl; cout << "max_size:" << str.max_size() << endl; return 0; }
// resize int main() { string str("I like c"); cout << str << endl; str.resize(str.size() + 2, '+'); cout << str << endl; str.resize(5); cout << str << endl; return 0; }
// clear int main() { string str("hello world"); cout << str << endl; cout << "str size:" << str.size() << endl; str.clear(); cout << str << endl; cout << "str size:" << str.size() << endl; return 0; }
// empty int main() { string nullstr; string str("hello world"); cout << nullstr.empty() << endl; cout << str.empty() << endl; return 0; }