- 常见构造
- string类对象的容量操作
- string类对象的访问及遍历操作
- string类对象的修改操作
1.string()
2.string(const char s)*
**3.string(const string&s) **
void Teststring()
{
string s1; // 构造空的string类对象s1
string s2("hello bit"); // 用C格式字符串构造string类对象s2
string s3(s2); // 拷贝构造s3
}
string类对象的容量操作
size:返回字符串有效字符长度
length:返回字符串有效字符长度
capacity:返回空间总大小
empty:检测字符串释放为空串,是返回true,否则返回false
clear:清空有效字符
reserve:为字符串预留空间
resize:将有效字符的个数该成n个,多出的空间用字符’ ’填充
void Teststring2()
{
string s;
// 测试reserve是否会改变string中有效元素个数
s.reserve(100);
cout << s.size() << endl;
cout << s.capacity() << endl;
// 测试reserve参数小于string的底层空间大小时,是否会将空间缩小
s.reserve(50);
cout << s.size() << endl;
cout << s.capacity() << endl;
}
void Teststring1()
{
string s("123456789");
s.resize(15);
cout << s.size() << endl;
cout << s.capacity() << endl;
cout << s << endl;
// 将s中有效字符个数缩小到5个
s.resize(5);
cout << s.size() << endl;
cout << s.capacity() << endl;
cout << s << endl;
}
void Teststring3()
{
string str("Hello Bit.");
str.reserve(111);
str.resize(5);
str.reserve(50);
cout << str.size() << ":" << str.capacity() << endl;
return 0;
}
这段代码结果是什么?
string类对象的访问及遍历操作operator[]:返回pos位置的字符,const string类对象调用
begin+end :begin获取一个字符的迭代器 + end获取最后一个字符下一个位置的迭代器
范围for:C++11支持更简洁的范围for的新遍历方式
oid Teststring()
{
string s("hello Bit");
// 3种遍历方式:
// 需要注意的以下三种方式除了遍历string对象,还可以遍历是修改string中的字符,
// 另外以下三种方式对于string而言,第一种使用最多
// 1. for+operator[]
for(size_t i = 0; i < s.size(); ++i)
cout<
cout<<*it<
string类对象的修改操作
operator+=:在字符串后追加字符串str
c_str:返回C格式字符串
find+pos从字符串pos位置开始往后找字符c,返回该字符在字符串中的位置
void Teststring()
{
string str;
str += 'b'; // 在str后追加一个字符'b'
str += "it"; // 在str后追加一个字符串"it"
cout< 


