string类:
1.string是表示字符串的类;
2.string类的接口与常规容器接口基本相同
3.string底层实现由basic_string模板类实现;
string的构造
string() //用于构造string类的对象;
string(const char*s) //用C-string构造string;
string(size_t n,char c) //string类中含n个c字符
string(const string&s) // 拷贝构造函数(深拷贝)
string s1;
string s2("hello world");
string s3(s2);
string类的容量基本操作:
size //返回字符串有效字符长度
length //返回字符串有效长度
capacity //返回空间的大小
string s("hello world");
cout << s.size() << endl;
cout << s.length() << endl;
cout << s.capacity() << endl;
cout << s << endl;
**注意:**使用cout需包string的头文件,否则cout无法重载;
empty //检测字符串是否为空,return ture or false;
clear //清空有效字符
string s("hello world");
cout << s.size() << endl;
cout << s.length() << endl;
cout << s.capacity() << endl;
cout << s << endl;
//清空字符串,空间不改变
s.clear();
cout << s.empty() << endl;
cout << s.size() << endl;
cout << s.capacity() << endl;
clear只是将有效字符串进行清空,并没有改变空间大小;
empty判断为空返回1;
reserve //为字符串预留空间
resize(size_t n ,char c) //将有效字符该为n个,多出来的用字符c填补
s.resize(15, 'w');//扩充到15个有效字符,多处位置为w
cout << s.size() << endl;
cout << s.capacity() << endl;
cout << s << endl;
s.reserve(100);
cout << s.size() << endl;
cout << s.capacity() << endl;
运行结果:
可以看到reserve并不会将原来的有效元素改变,只是增容;当reserve的值小于当前空间,不会起到作用(合理利用可以避免增容开销)
string类对象的访问以及遍历
访问
operator[pos] //返回pos位置的字符
string s1("hello world");
const string s2("HELLO WORLD");
cout << s1 << "-" << s2 << endl;
cout << s1[0] << "-" << s2[0] << endl;
s1[0] = 'H';
cout << s1[0] << "-" << s2[0] << endl;
与c语言访问数组类似,可以使用重载后的[]访问;
遍历
三种方式
使用operator[] ,配合循环
begin() + end() // begin返回一个字符迭代器,end返回最后一个字符下一个位置的迭代器
范围for //适用于c++11;
//operator[]
for (size_t i= 0; i < s1.size(); ++i)
{
cout << s1[i] << endl;
}
//迭代器
string::iterator it = s1.begin();
while (it != s1.end())
{
cout << *it << endl;
++it;
}
//范围for
{
for (auto e : s1)
{
cout << e << endl;
}
}
}
可以看到三种方式都可以完成遍历,且可以修改字符。
string类对象的修改操作
push_back //在字符串后尾插字符c
append //在字符串后追加一个字符串
operator+= //在字符串后追加字符串str
c str //返回c格式字符串
find + npos//从字符串pos位置开始找字符c,返回该字符串的位置
substr //在str中从pos位置开始,截取n个字符,然后返回。
string str;
str.push_back(' ');
str.append("hello ");
str += 'w';
str += "orld";
cout << str << endl;
cout << str.c_str() << endl;
push_back接口与append的区别是前者插入字符,后者插入字符串
operator+=可以同时实现上面俩个接口,区别为插入字符使用‘’ 单引号,插入字符串需使用“”,如果使用错误,编译器会发生截断。
find + npos//从字符串pos位置开始找字符c,返回该字符串的位置
substr //在str中从pos位置开始,截取n个字符,然后返回。
string url("https://editor.youkuaiyun.com/md/?articleId=106225126");
size_t pos = url.find("://");
if (pos != string::npos)
{
cout << url.substr(pos) << endl;
}
npos 为string里面的一个静态成员变量默认为-1;