1.概述
首先谈谈为什么要使用和学习string?
2.用法介绍
size_t pos:表示无符号string对象的下标
size_t npos:表示无符号-1,表示2^32
(InputIterator first, InputIterator last):迭代器:表示一个区间
//构造函数constructor
void test_string1()
{
string s1;//无参的构造函数
string s2("hello world");//用一个字符串构造s2
string s3("happy", 3);//使用字符串的前三个字符构造s3
string s4(4, 'x');//用4个x构造s4
string s5(s2);//拷贝构造
string s6(s2, 6, 5);//表示用s2的第6个字符开始的3个字符构造
string s7(s2.begin(), s2.end());//用迭代器构造
cout << "s1:" << s1 << endl;
cout << "s2:" << s2 << endl;
cout << "s3:" << s3 << endl;
cout << "s4:" << s4 << endl;
cout << "s5:" << s5 << endl;
cout << "s6:" << s6 << endl;
cout << "s7:" << s7 << endl;
}

2.2用于string对象一些容量操作
| size | 返回字符串的有效字符个数 |
| length | 返回字符串的有效字符长度 |
| capacity | 返回字符串的有效空间容量大小 |
| empty | 检测字符串是否为空串,true表示空,false表示非空 |
| clear | 清理有效字符 |
| reserve | 为字符串提前开辟空间 |
| resize | 将有效字符的个数改成n个,多出的空间用字符c补充 |
void test_string2()
{
//size,length
string s1("happy newyear");
cout << "有效字符数据个数:" << s1.size() << endl;
//s1.length()和s1.size()用法相同,功能类似
cout << "空间容量大小:" << s1.capacity() << endl;
string s2;
//empty
cout << "s1是否为空:" << s1.empty() << endl;
cout << "s2是否为空:" << s2.empty() << endl;
//clear
s1.clear();
cout <<"clear:"<< s1 << endl;
}

使用一段代码来观察reserve的功能:
//vs2022环境下
void test_string3()
{
//构建string时,如果提前已经知道string中大概需要
//放多少个元素,可以提前将string中的空间设置好
string s;
//s.reserve(100);
size_t sz = s.capacity();//计算没插入元素之前s的容量大小
cout << "makeing s grow:\n";
for (int i = 0; i < 100; i++)
{
s.push_back('c');
if (sz != s.capacity())
{
sz = s.capacity();//扩容后重置sz
cout << "capacity changeed:" << sz << endl;
}
}
}
没有提前开空间:

提前开空间:

resize功能:
//1.resize表示有效数据的大小,会开空间
string s1("hello world");
cout <<"s1的容量:"<< s1.capacity() << endl;
s1.resize(100);//vs下编译器会根据内存对齐原则,适当开空间(>=100)
cout << "s1的容量:" << s1.capacity() << endl;
//vs下编译结果:
//s1的容量:15
//s1的容量:111
//2.默认情况下会有效字符后面加'\0',这个字符可以自己选定
string s2("xxxxx");
s2.resize(32, 'y');
cout << s2 << endl;
//s2.resize(32);
//默认情况下:xxxxx'\0'.......
//编译结果:xxxxxyyyyyyyyyyyyyyyyyyyyyyyyyyy
2.3 string的插入接口函数(push_back,append,operator+=,insert)
//push_back尾插一个字符
string s1("helllo world");
s1.push_back('x');
s1.push_back('y');
s1.push_back('z');
cout << "s1:" << s1 << endl;
//append尾插一个字符串
string s2("I have a lovely");
s2.append("cat");
cout << "s2:" << s2 << endl;
//operator+=尾插一个字符/字符串
string s3("hello dog");
s3 += "ll";
s3 += 'w';
cout <<"s3:" << s3 << endl;
//insert在任意一个位置插入数据
string s4("hello world");
s4.insert(5, "djhk");
cout <<"s4:"<< s4 << endl;

2.4string的遍历和打印:下标访问operator[]和迭代器iterator
void test_string5()
{
//下标访问 运算符重载
string s1("hello world");
cout << "下标访问:";
for (int i = 0; i < s1.size(); i++)
{
cout << s1[i] ;
}
cout << endl;
//迭代器
string s2("quick and slow");
string::iterator it = s2.begin();
cout << "迭代器访问:";
while (it != s2.end())
{
cout << *it ;
it++;
}
cout << endl;
//范围for原理->调用迭代器
cout << "范围for: ";
for (auto e : s2)
{
cout << e ;
}
}

2.5 string的删除接口函数:erase()
void test_string6()
{
string s1("hello world");
s1.erase(1, 3);//删除下标3到下标的字符
cout << "s1:" << s1 << endl;
string s2("i have a pig");
s2.erase(2);//从下标为2的位置一直删完
cout << "s2:" << s2 << endl;
string s3("you are right");
s3.erase(s3.begin());//删除迭代器位置的字符
cout << "s3:"<<s3 << endl;
//删除迭代器区间的字符
s3.erase(s3.begin(), s3.end() - 3);
cout << "s3:" << s3 << endl;
}

2.6string的查找接口:find() rfind()(常用)
//从下标为pos位置开始找string对象str
size_t find(const string& str, size_t pos = 0) const;
//从下标为pos位置开始找字符串s
size_t find(const char* s, size_t pos = 0) const;
//从下标为pos位置开始找字符串s前n个字符串
size_t find(const char* s, size_t pos, size_t n) const;
//从下标为pos位置找字符c
size_t find(char c, size_t pos = 0) const;
//rfind倒着找
size_t rfind(const string & str, size_t pos = npos) const;
size_t rfind(const char* s, size_t pos = npos) const;
size_t rfind(const char* s, size_t pos, size_t n) const;
size_t rfind(char c, size_t pos = npos) const;
void test_string7()
{
string s1("Since ancient times, deep feeling can not stay");
string s2("time");
size_t len1 = s1.find(s2, 0);//运行结果:len1: 14
cout << "len1: " << len1 << endl;
size_t len2 = s1.find("deep", 3);//运行结果:len2: 21
cout << "len2: " << len2 << endl;
size_t len3 = s1.find('a', 0);
cout << "len3: " << len3 << endl;//运行结果:len3: 6
size_t len4 = s1.find("not stay", 4, 4);
cout << "len4: " << len4 << endl;//运行结果:len4: 38
}
find()函数和substr()函数的一个小的运用场景:
//取出协议 域名 uri
string url("https://cplusplus.com/reference/string/string/erase/");
string protocol;
size_t pos1 = url.find("://");
if (pos1 != string::npos)
{
protocol = url.substr(0, pos1);
cout << "协议为:" << protocol << endl;
}
else
{
cout << "非法url" << endl;
return;
}
string domain;
size_t pos2 = url.find('/', pos1 + 3);
if (pos2 != string::npos)
{
domain = url.substr(pos1+3, pos2-pos1-3);
cout << "域名为:" << domain << endl;
}
string uri;
size_t pos3 = pos2 + 1;
if (pos3 != string::npos)
{
domain = url.substr(pos3);
cout << "uri:" << domain << endl;
}

2.7string分割:strtok() ,substr()
void test_string8()
{
char str[80] = "sort - fail - mail";
//字符串里可以是一个分隔符,也可以是分隔符的集合
const char s[2] = "-";
/* 获取第一个子字符串 */
char* token = strtok(str, s);
/* 继续获取其他的子字符串 */
while (token != NULL) {
printf("%s\\n", token);
token = strtok(NULL, s);
}
}
//运行结果:sort \n fail \n mail\n
cout << endl;
//substr切割字符串
//string substr(size_t pos = 0, size_t len = npos) const;
string s1("hello world");
s1.substr(2, 7);
cout << s1 << endl;
string s2("pig and monkey");
s2.substr(3);
cout << s2 << endl;
//运行结果:hello world
// pig and monkey
3.整个string类底层实现
#include <iostream>
using namespace std;
#include <assert.h>
#include <string>
namespace yht
{
class string
{
public:
typedef char* iterator;
typedef const char* const_iterator;
//有参构造函数
//string(const char* str)
// :_str(new char[strlen(str)+1])
// ,_capacity(strlen(str))
// ,_size(strlen(str))
//{
// strcpy(_str, str);
//}
////无参构造
//string()
// :_str(new char[1])
// ,_capacity(0)
// ,_size(0)
//{
// _str[0] = '\0';
//}
//全缺省构造函数
string(const char* str = "")
{
_size = strlen(str);
_capacity = _size;
_str=new char[_capacity + 1];
strcpy(_str, str);
}
//析构函数
~string()
{
delete[] _str;
_str = nullptr;
_capacity = _size = 0;
}
const char* c_str() const
{
return _str;
}
size_t size() const
{
return _size;
}
size_t capacity() const
{
return _capacity;
}
char& operator[](size_t pos)
{
return _str[pos];
}
const char& operator[](size_t pos) const
{
return _str[pos];
}
iterator begin()
{
return _str;
}
iterator end()
{
return _str + _size;
}
const iterator begin() const
{
return _str;
}
const iterator end() const
{
return _str + _size;
}
//拷贝构造函数
//打工人
/*string(const string& s)
:_str(new char[strlen(s._str)+1])
,_size(s._size)
,_capacity(s._capacity)
{
strcpy(_str, s._str);
}*/
void swap(string& s)
{
::swap(_str, s._str);
::swap(_size, s._size);
::swap(_capacity, s._capacity);
}
//老板
string(const string& s)
:_str(nullptr)
,_capacity(0)
,_size(0)
{
string tmp(s._str);
swap(tmp);
}
//赋值运算符重载
//打工人
//string operator=(const string& s)
//{
// if (this != &s)
// {
// delete[] _str;
// _str = new char[strlen(s._str) + 1];
// strcpy(_str, s._str);
// _capacity = s._capacity;
// _size = _size;
// }
// return *this;
//}
////老板
//string operator=(const string& s)
//{
// if (this != &s)
// {
// string tmp(s._str);
// swap(tmp);
// }
// return *this;
//}
string& operator=(string s)
{
swap(s);
return *this;
}
void reserve(size_t n)
{
if (n > _capacity)
{
char* tmp = new char[n + 1];
strcpy(tmp, _str);
delete[] _str;
_capacity = n;
_str = tmp;
}
}
void push_back(char ch)
{
if (_size == _capacity)
{
reserve(_capacity == 0 ? 4 : _capacity * 2);
}
_str[_size] = ch;
_size++;
_str[_size] = '\0';
}
string& operator+=(char ch)
{
push_back(ch);
return *this;
}
void append(const char* str)
{
size_t len = strlen(str);
if (len + _size > _capacity)
{
reserve(len + _size);
}
strcpy(_str + _size, str);
_size += len;
}
string& operator+=(const char* str)
{
append(str);
return *this;
}
string& insert(size_t pos, char ch)
{
if (_size == _capacity)
{
reserve(_capacity == 0 ? 4 : _capacity * 2);
}
int end = _size + 1;
while (end > pos)
{
_str[end] = _str[end - 1];
end--;
}
_str[pos] = ch;
_size++;
return *this;
}
string& insert(size_t pos, const char* str)
{
size_t len = strlen(str);
if (len + _size > _capacity)
{
reserve(len + _size);
}
int end = _size + len;
while (end>=pos+len)
{
_str[end] = _str[end - len];
end--;
}
strncpy(_str + pos, str, len);
_size += len;
return *this;
}
string& erase(size_t pos, size_t len = npos)
{
if (len == npos || len + pos >= _size)
{
_str[pos] = '\0';
_size = pos;
}
else
{
strcpy(_str + pos, _str + pos + len);
_size -= len;
}
return *this;
}
void clear()
{
_size = 0;
_str[0] = '\0';
}
size_t find(char ch, size_t pos = 0) const
{
for (; pos <= size(); pos++)
{
if (_str[pos] == ch)
return pos;
}
return npos;
}
size_t find(const char* sub, size_t pos = 0) const
{
char* str = strstr(_str + pos, sub);
if (str != NULL)
{
return str - _str;
}
else
{
return npos;
}
}
string substr(size_t pos, size_t len = npos)
{
assert(pos < _size);
size_t realLen = len;
string s;
if (len == npos || len + pos > _size)
{
realLen = _size - pos;
}
for (size_t i = 0; i < realLen; i++)
{
s += _str[pos + i];
}
return s;
}
bool operator>(const string& s) const
{
return strcmp(_str,s._str) > 0;
}
bool operator==(const string& s) const
{
return strcmp(_str, s._str) == 0;
}
bool operator!=(const string& s) const
{
return !(*this == s);
}
bool operator>=(const string& s) const
{
return (*this == s) && (*this > s);
}
bool operator<(const string& s) const
{
return !(*this >= s);
}
bool operator<=(const string& s) const
{
return !(*this > s);
}
void resize(size_t n, char ch = '\0')
{
if (n > _capacity)
{
reserve(n);
for (; _size < n; _size++)
{
_str[_size] = ch;
}
_str[_size] = '\0';
}
else
{
_str[n] = '\0';
_size = n;
}
}
private:
char* _str;
size_t _capacity;
size_t _size;
const static size_t npos = -1;
};
ostream& operator<<(ostream& out, const string& s)
{
for (auto ch : s)
{
cout << ch;
}
return out;
}
istream& operator>>(istream& in, string& s)
{
s.clear();
char ch;
ch = in.get();
char buff[32];
int i = 0;
while (ch != ' ' && ch != '\n')
{
buff[i++] = ch;
if (i == 31)
{
buff[i] = '\0';
s += buff;
i = 0;
}
ch = in.get();
}
buff[i] = '\0';
s += buff;
return in;
}
}

1864




被折叠的 条评论
为什么被折叠?



