一、string类的常用接口说明
1、string类对象的常见构造
函数名称 | 功能说明 |
---|---|
string() | 构造空的string类对象,即空字符串 |
string(const char* s) | 用C-string来构造string类对象 |
string(size_t n, char c) | string类对象中包含n个字符c |
string(const string& s) | 拷贝构造函数 |
string(const string& s, size_t n) | 用s中的前n个字符构造新的string类对象 |
void TestString1()
{
string s1; //构造空的string类对象s1
cout << s1 << endl;
string s2("hello world"); //用C格式字符串构造string类对象s2
cout << s2 << endl;
string s3(10, 'a'); //用10个字符'a'构造string类对象s3
cout << s3 << endl;
string s4(s2); //拷贝构造s4
cout << s4 << endl;
string s5(s2, 5); //用s3中前5个字符构造string类对象s5
cout << s5 << endl;
}
2、string类对象的容量操作
函数名称 | 功能说明 |
---|---|
size_t size() const | 返回字符串有效字符长度 |
size_t length() const | 返回字符串有效字符长度 |
size_t capacity() const | 返回空间总大小 |
bool empty() const | 检测字符串释放为空串,是返回true,否返回false |
void clear() | 清空有效字符串 |
void resize(size_t n, char c) | 将有效字符的个数改成n个,多出的空间用字符c填充 |
void resize(size_t n) | 将有效字符的个数改成n个,多出的空间用0填充 |
void reserve(size_t res_arg = 0) | 为字符串预留空间 |
void TestString2()
{
string s("hello world");
cout << s.length() << endl;
cout << s.size() << endl;
cout << s.capacity() << endl;
cout << s << endl;
//将s中的字符串清空,注意清空时只是将size清0,不改变底层空间的大小
s.clear();
cout << s.size() << endl;
cout << s.capacity() << endl;
cout << s << endl;
//将s1中有效字符个数增加到10个,多出位置用'a'进行填充
string s1("hello");
s1.resize(10, 'a');
cout << s1.size() << endl;
cout << s1.capacity() << endl;
cout << s1 << endl;
//将s1中有效字符个数增加到15个,多出位置用缺省值'\0'进行填充
s1.resize(15);
cout << s1.size() << endl;
cout << s1.capacity() << endl;
cout << s1 << endl;
//将s1中有效字符个数缩小到5个
s1.resize(5);
cout << s1.size() << endl;
cout << s1.capacity() << endl;
cout << s1 << endl;
string s2;
//测试reserve是否会改变string中有效元素个数
s2.reserve(100);
cout << s1.size() << endl;
cout << s1.capacity() << endl;
//测试reserve参数小于string的底层空间大小时,是否会将空间缩小
s2.reserve(50);
cout << s1.size() << endl;
cout << s1.capacity() << endl;
}
注:(1)size()与length()方法底层实现原理完全相同,引入size()的原因是为了与其他容器的接口保持一致,一般情况下基本都用size()
(2)clear()只是将string中有效字符清空,不改变底层空间大小
(3)reserve:为string预留空间,不改变有效元素个数,当reserve的参数小于string的底层空间总大小时,reserve不会改变容量大小
3、string类对象的访问操作
函数名称 | 功能说明 |
---|---|
char& operator[](size_t pos) | 返回pos位置的字符,const string类对象调用 |
const char& operator[](size_t pos) const | 返回pos位置的字符,非const string类对象调用 |
void TestString3()
{
string s1("hello world");
const string s2("hello world");
cout << s1 << " " << s2 << endl;
cout << s1[0] << " " << s2[0] << endl;
s1[0] = 'H';
cout << s1 << endl;
for (size_t i = 0; i < s1.size(); i++)
{
cout << s1[i] << " ";
}
cout << endl;
}
//迭代器
void Test()
{
//string迭代器
string s("hello world");
string::iterator it = s.begin();
while (it != s.end())
{
cout << *it << " ";
++it;
}
cout << endl;
//vector迭代器
vector<int> v(10, 5);
string::iterator vit = s.begin();
while (vit != s.end())
{
cout << *vit << " ";
++vit;
}
cout << endl;
//list迭代器
list<int> l(5, 10);
string::iterator lit = s.begin();
while (lit != s.end())
{
cout << *lit << " ";
++lit;
}
cout << endl;
}
注:iterator不可定义为全局的,因为string,vector,list都有iterator,使用迭代器时必须指明其属于哪一个类域
4、string类对象的修改操作
函数名称 | 功能说明 |
---|---|
void push_back(char c) | 在字符串后尾插字符c |
string& append(const char* s) | 在字符串后追加一个字符串 |
string& operator+=(const string& str) | 在字符串后追加字符串str |
string& operator+=(const char* s) | 在字符串后追加C个数字符串 |
string& operator+=(char c) | 在字符串后追加字符c |
const char* c_str() const | 返回c格式字符串 |
size_t find(char c, size_t pos = 0) const | 从字符串pos位置开始往后找字符c,返回该字符在字符串中的位置 |
size_t rfind(char c, size_t pos = npos) | 从字符串pos位置开始往前找字符c,返回该字符在字符串中的位置 |
string substr(size_t pos = 0, size_t n = npos)const | 在str中从pos位置开始,截取n个字符,然后将其返回 |
void TestString4()
{
string str;
str.push_back(' '); //在str后插入空格
str.append("hello"); //在str后追加一个字符"hello"
str += 'w'; //在str后追加一个字符"w"
str += "orld"; //在str后追加一个字符串"orld"
cout << str << endl;
cout << str.c_str() << endl; //以c语言的方式打印字符串
//获取file的后缀
string file("string.cpp");
size_t pos = file.rfind('.');
string suffix(file.substr(pos, file.size() - pos));
cout << suffix << endl;
//npos是string里面的一个静态成员变量
//static const size_t npos = -1;
//取出url中的域名
string url("http://www.cplusplus.com/reference/string");
cout << url << endl;
size_t start = url.find("://");
if (start == string::npos)
{
cout << "invalid url" << endl;
return;
}
start += 3;
size_t finish = url.find('/', start);
string address = url.substr(start, finish - start);
cout << address << endl;
//删除url的协议前缀
pos = url.find("://");
url.erase(0, pos + 3);
cout << url << endl;
}
//利用reserve提高插入数据的效率,避免增容带来的开销
void TestPushBack()
{
string s;
size_t sz = s.capacity();
cout << "making s grow:" << endl;
for (int i = 0; i < 100; i++)
{
s += 'c';
if (sz != s.capacity())
{
sz = s.capacity();
cout << "capacity changed: " << sz << endl;
}
}
}
void TestPushBack_P()
{
string s;
s.reserve(100);
size_t sz = s.capacity();
cout << "making s grow:" << endl;
for (int i = 0; i < 100; i++)
{
s += 'c';
if (sz != s.capacity())
{
sz = s.capacity();
cout << "capacity changed: " << sz << endl;
}
}
}
注:对string操作时,如果能够大概预估到放多少字符,可以先通过reserve把空间预留好
5、string类非成员函数
函数 | 功能说明 |
---|---|
operator+ | 尽量少用,因为效率低 |
operator>> | 输入运算重载符 |
operator<< | 输出运算重载符 |
getline | 获取一行字符串 |
relational operators | 大小比较 |
二、string类的模拟实现
class String
{
public:
String(const char* str = "")
{
//构造string类对象时,如果传递nullptr指针,认为此程序非法,此处断言下
if (nullptr == str)
{
assert(false);
return;
}
_str = new char[strlen(str) + 1];
//加1是因为还有'\0'
strcpy(_str, str);
}
~String()
{
if (_str)
{
delete[] _str;
_str = nullptr;
}
}
private:
char* _str;
};
void TestString()
{
String s1("hello world");
String s2(s1);
}
上述String类没有显式定义其拷贝函数,此时编译器会合成默认的,当用s1构造s2时,编译器会调用默认的拷贝构造函数。最终导致的问题是,s1、s2共用同一块空间,在释放时同一块空间释放多次而引起程序崩溃。
1、浅拷贝
浅拷贝:也称位拷贝,编译器只是将对象中的值拷贝过来。如果对象中管理资源,最后就会导致多个对象共享同一份资源,当一个对象销毁时就会将该资源销毁掉,而此时另一些对象不知道该资源已经被释放,以为还有效,所以当继续对资源进行操作时,就会发生访问违规。
2、深拷贝
如果一个类中涉及到资源的管理,其拷贝构造函数、赋值运算符重载以及析构函数必须要显示给出。
3、传统版写法的String类
class String
{
public:
String(const char* str = "")
{
//构造string类对象时,如果传递nullptr指针,认为此程序非法,此处断言下
if (nullptr == str)
{
assert(false);
return;
}
_str = new char[strlen(str) + 1];
//加1是因为还有'\0'
strcpy(_str, str);
}
String(const String& s)
:_str(new char[strlen(s._str), + 1])
{
strcpy(_str, s._str);
}
String& operator=(const String& s)
{
if (this != &s)
{
char* pStr = new char[strlen(s._str) + 1];
strcpy(pStr, s._str);
delete[] _str;
_str = pStr;
}
return *this;
}
~String()
{
if (_str)
{
delete[] _str;
_str = nullptr;
}
}
private:
char* _str;
};
4、现代版写法的String类
class String
{
public:
String(const char* str = "")
{
if (nullptr == str)
{
str = "";
}
_str = new char[strlen(str) + 1];
//加1是因为还有'\0'
strcpy(_str, str);
}
String(const String& s)
:_str(nullptr)
{
String strTmp(s._str); //构造函数
swap(_str, strTmp);
}
String& operator=(String& s)
{
swap(_str, s._str);
return *this;
}
~String()
{
if (_str)
{
delete[] _str;
_str = nullptr;
}
}
private:
char* _str;
};