string的使用与模拟实现
总引
在前面C++的学习中,我们已经将C++中最基础的知识了解的差不多了。从今天开始我们就要开始学习C++中最重要也是最经典的STL了即标准模板库,而STL包含了我们以前学习的数据结构等知识。所以对于STL的学习我们不仅要知道他是如何使用的更要知道他的底层逻辑并模拟实现他,而string则是STL中的入门板块。
一.string简介
C语言中,字符串是以’\0’结尾的一些字符的集合,为了操作方便,C标准库中提供了一些str系列的库函数,但是这些库函数与字符串是分离开的,不太符合OOP的思想,而且底层空间需要用户自己管理,稍不留神可能还会越界访问。
而C++中字符串的使用通常就是利用string类进行操作,而且在常规工作中,为了简单、方便、快捷,基本都使用string类,很少有人去使用C库中的字符串操作函数。
注意:
- string是表示字符串的字符串类
- 该类的接口与常规容器的接口基本相同,再添加了一些专门用来操作string的常规操作。 比特就业课
- string在底层实际是:basic_string模板类的别名,typedef basic_string<char, char_traits, allocator> string;
- 不能操作多字节或者变长字符的序列。
二.string的使用
2.1string类对象的构造函数
函数名称 | 功能介绍 |
---|---|
string()(常用) | 构造空的string类对象,即空字符串 |
string(const char* str)(常用) | 用C-string来构造string类对象 |
string(size_t n,char ch) | string类对象中包含n个字符c |
string(const string& s)(常用) | 拷贝构造函数 |
#include <iostream>
#include <string>
using namespace std;
int main()
{
string s;//构造一个空的string类
string s1("hello world");//用字符串构造一个string类
string s2(5, 'x');//用n个字符构造一个string类
string s3(s1);//拷贝构造
cout << s << endl;
cout << s1 << endl;
cout << s2 << endl;
cout << s3 << endl;
return 0;
}
2.2 string类对象的容量操作
函数名称 | 功能介绍 |
---|---|
size(常用) | 返回字符串的有效字符长度 |
length | 返回字符串的有效字符长度 |
capacity(常用) | 返回字符串的容量大小 |
empty | 检测字符串释放为空串,是返回true,否则返回false |
clear(常用) | 清空字符串 |
reserve(常用) | 为字符串预留空间 |
resize(常用) | 将有效字符的个数该成n个,多出的空间用字符c填充 |
void test_string2()
{
string s("hello world");
cout << s.size() << endl;
cout << s.length() << endl;
cout << s.capacity() << endl;
cout << s.empty() << endl;
s.reserve(5);
cout << s << endl;
s.resize(20, 'x');
cout << s << endl;
}
int main()
{
test_string2();
return 0;
}
注意:
- size()与length()方法底层实现原理完全相同,引入size()的原因是为了与其他容器的接口保持一致,一般情况下基本都是用size()。
- clear()只是将string中有效字符清空,不改变底层空间大小。
- resize(size_t n) 与 resize(size_t n, char c)都是将字符串中有效字符个数改变到n个,不同的是当字符个数增多时:resize(n)用0来填充多出的元素空间,resize(size_tn, charc)用字符c来填充多出的元素空间。注意:resize在改变元素个数时,如果是将元素个数增多,可能会改变底层容量的大小,如果是将元素个数减少,底层空间总大小不变。
- reserve(size_t res_arg=0):为string预留空间,不改变有效元素个数,当reserve的参数小于 string的底层空间总大小时,reserver不会改变容量大小。
2.3 string类对象的访问及遍历操作
函数名称 | 功能介绍 |
---|---|
operator[] | 返回pos位置的字符,const string类对象调用 |
begin+end | begin获取一个字符的迭代器 + end获取最后一个字符下一个位置的迭代器 |
rbegin+rend | begin获取一个字符的迭代器 + end获取最后一个字符下一个位置的迭代器 |
范围for | C++11支持更简洁的范围for的新遍历方式 |
void test_string3()
{
string s("hello world");
//第一种迭代方法:重载[]
for (size_t i = 0; i < s.size(); i++)
{
cout << s[i];
}
cout << endl;
//第二种迭代方法:迭代器
string::iterator it = s.begin();
while (it != s.end())
{
cout << *it;
++it;
}
cout << endl;
//第三种迭代方法:范围for
for (auto ch : s)
{
cout << ch;
}
cout << endl;
}
int main()
{
test_string3();
return 0;
}
2.4 string类对象的修改操作
函数名称 | 功能介绍 |
---|---|
push_back | 在字符串后尾插字符c |
append | 在字符串后追加一个字符串 |
operator+=(常用) | 在字符串后追加字符串str |
find+npos(常用) | 从字符串pos位置开始往后找字符c,返回该字符在字符串中的位置 |
c_str(常用) | 返回C格式字符串 |
rfind | 从字符串pos位置开始往前找字符c,返回该字符在字符串中的位置 |
substr(常用) | 在str中从pos位置开始,截取n个字符,然后将其返回 |
void test_string4()
{
string s("hello world");
cout << s << endl;
s.push_back(' ');//尾插一个字符
cout << s << endl;
s.append("xxx");//尾插一个字符串
cout << s << endl;
s += ' ';//尾插一个字符
cout << s << endl;
s += "you";//尾插一个字符串
cout << s << endl;
size_t n = s.find('o', 0);//从头找字符'0'并返回他的位置
cout << n << endl;
cout << s.c_str() << endl;//返回c格式的字符串
size_t i = s.rfind('o');//从尾找字符'0’并返回他的位置
cout << i << endl;
string s1 = s.substr(0, 5);//截取某段字符串
cout << s1 << endl;
}
int main()
{
test_string4();
return 0;
}
注意:
- 在string尾部追加字符时,s.push_back© / s.append(1, c) / s += 'c’三种的实现方式差不多,一般 情况下string类的+=操作用的比较多,+=操作不仅可以连接单个字符,还可以连接字符串。
- 对string操作时,如果能够大概预估到放多少字符,可以先通过reserve把空间预留好。
2.5 string类非成员函数
函数名称 | 功能介绍 |
---|---|
operator+ | 尽量少用,因为传值返回,导致深拷贝效率低 |
operator<< | 输入运算符重载 |
operator>> | 输出运算符重载 |
getline | 获取一行字符串 |
operator<(大小比较函数) | 比较大小 |
上面的几个接口大家了解一下即可,在我们刷题时偶尔会使用到它们,string的接口就介绍到这里我们只介绍了string类中的一些常用且重要的接口,其余的接口在使用到时我们查文档即可。
三.string的模拟实现
3.1string类对象的构造函数
#define _CRT_SECURE_NO_WARNINGS 1
#include <iostream>
#include <string>
using namespace std;
#include <stdlib.h>
namespace Std
{
class String
{
public:
String(const char* str = "")
:_size(strlen(str))
, _capacity(_size)
{
_str = new char[_capacity + 1];
strcpy(_str, str);
}
~String()
{
delete[] _str;
_str = nullptr;
_size = _capacity = 0;
}
//传统写法
/*String(const String& s)
{
_str = new char[s._capacity + 1];
strcpy(_str, s._str);
_size = s._size;
_capacity = s._capacity;
}*/
/*String& operator=(String& s)
{
if (&s != this)
{
char* tmp = new char[s._capacity + 1];
strcpy(tmp, s._str);
delete[] _str;
_str = tmp;
_size = s._size;
_capacity = s._capacity;
return *this;
}
}*/
//现代写法
void Swap(String& s)
{
std::swap(_str, s._str);
std::swap(_size, s._size);
std::swap(_capacity, s._capacity);
}
String(const String& s)
:_str(nullptr)
,_size(0)
,_capacity(0)
{
String tmp(s._str);
Swap(tmp);
}
String& operator= (String tmp)
{
Swap(tmp);
return *this;
}
private:
char* _str;
size_t _size;
size_t _capacity;
};
}
using namespace Std;
int main()
{
String s1("hello world");
String s2(s1);
return 0;
}
3.2string类的容量操作
size_t size()
{
return _size;
}
size_t capacity()
{
return _capacity;
}
void clear()
{
_str[0] = '\0';
_size = 0;
}
void reserve(size_t n)
{
if (n > _capacity)//n小于容量时不做处理
{
char* tmp = new char[n + 1];
strcpy(tmp, _str);
delete[] _str;
_str = tmp;
_capacity = n;
}
}
void resize(size_t n, char ch = '\0')
{
if (n < _capacity)//删除
{
_str[n] = '\0';
_size = n;
}
else
{
reserve(n);
for (size_t i = _size; i < n; i++)
{
_str[i] = ch;
}
_size = n;
_str[n] = '\0';
}
}
3.3string类对象的访问及遍历操作
class String
{
public:
size_t operator[](size_t n)
{
assert(n < _size);
return _str[n];
}
typedef char* iterator;
typedef const char* const_iterator;
char* begin()
{
return _str;
}
char* end()
{
return _str + _size;
}
private:
char* _str;
size_t _size;
size_t _capacity;
};
}
using namespace Std;
int main()
{
String s1("hello world");
String::iterator it = s1.begin();
while (it != s1.end())
{
cout << *it;
it++;
}
cout << endl;
return 0;
}
3.4 string类对象的修改操作
class String
{
public:
const static size_t npos;
void push_back(char ch)
{
if (_size == _capacity)
{
reserve(_capacity == 0 ? 4 : _capacity * 2);
}
_str[_size] = ch;
_size++;
_str[_size] = '\0';
}
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+=(char ch)
{
push_back(ch);
return *this;
}
String& operator+=(const char* str)
{
append(str);
return *this;
}
void insert(size_t pos,const char ch)
{
if (_size == _capacity)
{
reserve(_capacity == 0 ? 4 : _capacity * 2);
}
//当pos为零时,因为为无符号整型所以end无法小于0导致死循环
/*size_t end = _size;
while (end >= pos)
{
_str[end+1] = _str[end];
end--;
}*/
//解决方法:
//1.更改挪位的方式
size_t end = _size+1;
while (end > pos)
{
_str[end] = _str[end-1];
end--;
}
//2.强转
/*size_t end = _size;
while (end >= (int)pos)
{
_str[end+1] = _str[end];
end--;
}*/
_str[pos] = ch;
++_size;
}
void insert(size_t pos,const char* str)
{
int len = strlen(str);
if (_size + len > _capacity)
{
reserve(_size+len);
}
/*size_t end = _size;
while (end >= (int)pos)
{
_str[end + len] = _str[end];
end--;
}*/
size_t end = _size+len;
while (end > pos)
{
_str[end] = _str[end - len];
end--;
}
strncpy(_str + pos, str, strlen(str));
}
void erase(size_t pos,size_t len = npos)
{
assert(pos < _size);
if (len == npos || len + pos >= _size)
{
_str[pos] = '\0';
_size = pos;
}
else
{
size_t begin = pos + len;
while (begin <= _size)
{
_str[pos] = _str[begin];
pos++;
begin++;
}
_size -= len;
}
}
const char* c_str()const
{
return _str;
}
size_t find(const char* str,size_t pos)
{
char* p = strstr(_str + pos, _str);
if (p)
{
return p - _str;
}
else
{
return npos;
}
}
String substr(size_t pos = 0, size_t len = npos) const
{
String s;
size_t end = pos + len;
if (len == npos || len + pos > _size)
{
len = _size - pos;
end = _size;
}
s.reserve(len);
for (size_t i = pos; i <= end; i++)
{
s += _str[i];
}
return s;
}
private:
char* _str;
size_t _size;
size_t _capacity;
};
}
const static size_t npos = -1;
using namespace Std;
int main()
{
String s1("hello world");
cout << s1.c_str() << endl;
s1.push_back(' ');
cout << s1.c_str() << endl;
s1.append("and you");
cout << s1.c_str() << endl;
s1 += ' ';
cout << s1.c_str() << endl;
s1 += "ye";
cout << s1.c_str() << endl;
size_t n = s1.find("o", 0);
cout << n << endl;
String s = s1.substr(5, 20);
cout << s.c_str() << endl;
return 0;
}
3.5 string类非成员函数
ostream& operator<<(ostream& out, String& s)
{
for (auto ch : s)
{
out << ch;
}
out << endl;
}
istream& operator>>(istream& in, String& s)
{
//创建一个数组来暂时的存储数据以防止每次读取字符都要扩容
char buff[129];
char ch;
size_t i = 0;
ch = in.get();
while (ch != ' ' && ch != '/n')//空格或者换行结束
{
buff[i++] = ch;
if (i == 128)
{
buff[i] = '\0';
s += buff;
i = 0;
}
ch = in.get();
}
if (i != 0)
{
buff[i] = '\0';
s += buff;
}
return in;
}
bool operator<(const String& s1, const String& s2)
{
return strcmp(s1.c_str(), s2.c_str()) < 0;
}
bool operator>(const String& s1, const String& s2)
{
return strcmp(s1.c_str(), s2.c_str()) > 0;
}
bool operator==(const String& s1, const String& s2)
{
return strcmp(s1.c_str(), s2.c_str()) == 0;
}
bool operator<=(const String& s1, const String& s2)
{
return !(s1 > s2);
}
bool operator>=(const String& s1, const String& s2)
{
return !(s1 < s2);
}
bool operator>(const String& s1, const String& s2)
{
return !(s1 == s2);
}
总结
string的学习就结束了,我们在文档中学习string的使用从而让我们可以在日常中知道string各个接口的用处,到在底层里了解string各个的逻辑从而复现出每个接口。string只是STL的开始,也是STL中最为简单的一部分但也引出了一部分的问题让我们思考。下面我们会接着学习vector和list等经典的类。