一、string类的定义
1. string是表示字符串的字符串类。
2. 该类的接口与常规容器的接口基本相同,再添加了一些专门用来操作string的常规操作。
3. string在底层实际是:basic_string模板类的别名,typedef basic_string string。
4. 不能操作多字节或者变长字符的序列。
在使用string类时,必须包含#include头文件以及using namespace std;
二、string类的常用接口
2.1 string类对象的常见构造
void Teststring()
{
string s1; // 构造空的string类对象s1
string s2("hello bit"); // 用C格式字符串构造string类对象s2
string s3(s2); // 拷贝构造s3
}
2.2 string类对象的容量操作
void Teststring1()
{
// 注意:string类对象支持直接用cin和cout进行输入和输出
string s("hello, bit!!!");
cout << s.size() << endl;
cout << s.length() << endl;
cout << s.capacity() << endl;
cout << s << endl;
// 将s中的字符串清空,注意清空时只是将size清0,不改变底层空间的大小
s.clear();
cout << s.size() << endl;
cout << s.capacity() << endl;
// 将s中有效字符个数增加到10个,多出位置用'a'进行填充
// “aaaaaaaaaa”
s.resize(10, 'a');
cout << s.size() << endl;
cout << s.capacity() << endl;
// 将s中有效字符个数增加到15个,多出位置用缺省值'\0'进行填充
// "aaaaaaaaaa\0\0\0\0\0"
// 注意此时s中有效字符个数已经增加到15个
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 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;
}
注意:
1. size()与length()方法底层实现原理完全相同,引入size()的原因是为了与其他容器的接口保持一 致,一般情况下基本都是用size()。
2. clear()只是将string中有效字符清空,不改变底层空间大小。 3. resize(size_t n) 与 resize(size_t n, char c)都是将字符串中有效字符个数改变到n个,不同的是当字符个数增多时:resize(n)用0来填充多出的元素空间,resize(size_t n, char c)用字符c来填充多出的元素空间。注意:resize在改变元素个数时,如果是将元素个数增多,可能会改变底层容量的大小,如果是将元素个数减少,底层空间总大小不变。
4. reserve(size_t res_arg=0):为string预留空间,不改变有效元素个数,当reserve的参数小于 string的底层空间总大小时,reserver不会改变容量大小。
2.3 string类对象的访问及遍历操作
void Teststring3()
{
string s("hello Bit");
// 3种遍历方式:
// 需要注意的以下三种方式除了遍历string对象,还可以遍历是修改string中的字符,
// 另外以下三种方式对于string而言,第一种使用最多
// 1. for+operator[]
for (size_t i = 0; i < s.size(); ++i)
cout << s[i];
cout << endl;
// 2.迭代器
string::iterator it = s.begin();
while (it != s.end())
{
cout << *it;
++it;
}
cout << endl;
// C++11之后,直接使用auto定义迭代器,让编译器推到迭代器的类型
// 3.范围for
for (auto ch : s)
cout << ch;
cout << endl;
}
2.4 string类对象的修改操作![](https://img-blog.csdnimg.cn/direct/5812b288e82a4850a77b02b2eee98c7d.png)
void Teststring4()
{
string str;
str.push_back(' '); // 在str后插入空格
str.append("hello"); // 在str后追加一个字符"hello"
str += 'b'; // 在str后追加一个字符'b'
str += "it"; // 在str后追加一个字符串"it"
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/string/find/");
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;
}
注意:
1. 在string尾部追加字符时,s.push_back(c) / s.append(1, c) / s += 'c'三种的实现方式差不多,一般 情况下string类的+=操作用的比较多,+=操作不仅可以连接单个字符,还可以连接字符串。
2. 对string操作时,如果能够大概预估到放多少字符,可以先通过reserve把空间预留好。
2.5 string类非成员函数
std::getline (string):istream& getline (istream& is, string& str);从 is 中提取字符并将它们存储到 str 中,直到换行符 '\n'。
三、string类的模拟实现
#pragma once
#include <iostream>
#include <string>
#include<assert.h>
using namespace std;
namespace rab
{
class string
{
friend ostream& operator<<(ostream& out, string& s);
friend istream& operator>>(istream& in, string& s);
public:
typedef char* iterator;
typedef const char* const_iterator;
public:
string(const char* str = "") {
_size = strlen(str);
_capacity = _size;
_str = new char[_capacity + 1];
strcpy(_str, str);
}
string(const string& s) {
_str = new char[s._capacity + 1];
_size = s._size;
_capacity = s._capacity;
strcpy(_str, s._str);
}
string& operator=(const string& s) {
if (this != &s) {
char* tmp = new char[s._capacity + 1];
strcpy(tmp, s._str);
delete[] _str;
_str = tmp;
_size = s._size;
_capacity = s._capacity;
}
return *this;
}
~string() {
delete[]_str;
_str = nullptr;
_size = 0;
_capacity = 0;
}
// iterator
iterator begin() {
return _str;
}
iterator end() {
return _str + _size;
}
// modify
void push_back(char c) {
if (_size == _capacity) {
size_t newCapacity = _capacity == 0 ? 4 : _capacity * 2;
reserve(newCapacity);
}
_str[_size] = c;
_size++;
_str[_size] = '\0';
}
string& operator+=(char c) {
push_back(c);
return *this;
}
void append(const char* str) {
size_t len = strlen(str);
if (_size + len > _capacity) {
reserve(_size + len);
}
strcpy(_str + _size, str);
_size += len;
}
string& operator+=(const char* str) {
append(str);
return *this;
}
void clear() {
_size = 0;
_str[0] = '\0';
}
void swap(string& s) {
std::swap(_str, s._str);
std::swap(_size, s._size);
std::swap(_capacity, s._capacity);
}
const char* c_str()const {
return _str;
}
// capacity
size_t size()const {
return _size;
}
size_t capacity()const {
return _capacity;
}
bool empty()const {
if (_size == 0) {
return true;
}
else return false;
}
void resize(size_t n, char c = '\0') {
if (_size < n && n <= _capacity) {
for (size_t i = _size; i < n; i++) {
_str[i] = c;
}
_size = n;
_str[_size] = '\0';
}
else if (n > _capacity) {
reserve(n);
for (size_t i = _size; i < n; i++) {
_str[i] = c;
}
_str[_size] = '\0';
_size = n;
}
else {
_str[_size] = '\0';
_size = n;
}
}
void reserve(size_t n) {
if (n > _capacity) {
char* tmp = new char[n + 1];
strcpy(tmp, _str);
delete[]_str;
_str = tmp;
_capacity = n;
}
}
// access
char& operator[](size_t index) {
assert(index <= _size);
return _str[index];
}
const char& operator[](size_t index)const {
assert(index <= _size);
return _str[index];
}
//relational operators
bool operator<(const string& s);
bool operator<=(const string& s);
bool operator>(const string& s);
bool operator>=(const string& s);
bool operator==(const string& s);
bool operator!=(const string& s);
// 返回c在string中第一次出现的位置
size_t find(char c, size_t pos = 0) const {
for (size_t i = pos; i < _size; i++) {
if (_str[i] == c) {
return i;
}
}
}
// 返回子串s在string中第一次出现的位置
size_t find(const char* s, size_t pos = 0) const {
const char* ptr = strstr(_str + pos, _str);
if (ptr == nullptr) {
return npos;
}
else {
return ptr - _str;
}
}
// 在pos位置上插入字符c/字符串str,并返回该字符的位置
string& insert(size_t pos, char c) {
assert(pos <= _size);
if (_size == _capacity) {
size_t newCapacity = _capacity == 0 ? 4 : _capacity * 2;
reserve(newCapacity);
}
size_t end = _size + 1;
while (end > pos) {
_str[end] = _str[end - 1];
--end;
}
_str[pos] = c;
_size++;
return *this;
}
string& insert(size_t pos, const char* str) {
assert(pos <= _size);
size_t len = strlen(str);
if (_size + len > _capacity) {
reserve(_size + len);
}
int end = _size;
while (end >= (int)pos) {
_str[end + len] = _str[end];
end--;
}
strncpy(_str + pos, str, len);
_size += len;
return *this;
}
// 删除pos位置上的元素,并返回该元素的下一个位置
string& erase(size_t pos, size_t len) {
assert(pos < _size);
if (len == npos || pos + len >= _size) {
_str[pos] = '\0';
_size = pos;
}
else {
strcpy(_str + pos, _str + pos + len);
_size -= len;
}
return *this;
}
string substr(size_t pos = 0, size_t len = npos) const {
assert(pos < _size);
size_t end = pos + len;
if (len == npos || len + pos >= _size) {
end = _size;
}
string str;
str.reserve(end - pos);
for (size_t i = pos; i < end; i++) {
str += _str[i];
}
return str;
}
private:
char* _str;
size_t _capacity;
size_t _size;
const static size_t npos = -1;
};
ostream& operator<<(ostream& out, string& s) {
for (auto ch : s) {
out << ch;
}
return out;
}
istream& operator>>(istream& in, string& s) {
s.clear();
char buff[128];
char ch = in.get();
int i = 0;
while (ch != ' ' && ch != '\n') {
buff[i++] = ch;
if (i == 127) {
buff[i] = '\0';
s += buff;
i = 0;
}
ch = in.get();
}
if (i > 0) {
buff[i] = '\0';
s += buff;
}
return in;
}
}
四、string的深浅拷贝问题
4.1 浅拷贝
浅拷贝:也称位拷贝,编译器只是将对象中的值拷贝过来。如果对象中管理资源,最后就会导致多个对象共 享同一份资源,当一个对象销毁时就会将该资源释放掉,而此时另一些对象不知道该资源已经被释放,以为 还有效,所以当继续对资源进项操作时,就会发生发生了访问违规。
4.2 深拷贝
如果一个类中涉及到资源的管理,其拷贝构造函数、赋值运算符重载以及析构函数必须要显式给出。一般情况都是按照深拷贝方式提供。此时每个对象都有一份独立的资源,不要和其他对象共享。