目录
由于历史原因,string类并没有被规划到容器里面,但它的接口和大部分容器高度相似,并且也支持迭代器,所以我们也可以把他当作容器来使用,通过对string类的学习,后面也会对其他容器更加得心应手。
string类的文档:http://www.cplusplus.com/reference/string/string/?kw=string
补充两个小语法:auto和范围for
auto关键字
在早期C/C++中auto的含义是:使用auto修饰的变量,是具有自动存储器的局部变量,后来这个不重要了。C++11中,标准委员会变废为宝赋予了auto全新的含义即:auto不再是一个存储类型
指示符,而是作为一个新的类型指示符来指示编译器,auto声明的变量必须由编译器在编译时期推导而得。
用auto声明指针类型时,用auto和auto*没有任何区别,但用auto声明引用类型时则必须加&
当在同一行声明多个变量时,这些变量必须是相同的类型,否则编译器将会报错,因为编译器实际只对第一个类型进行推导,然后用推导出来的类型定义其他变量。
auto不能作为函数的参数,可以做返回值,但是建议谨慎使用
auto不能直接用来声明数组
范围for
对于一个有范围的集合而言,由程序员来说明循环的范围是多余的,有时候还会容易犯错误。因此C++11中引入了基于范围的for循环。for循环后的括号由冒号" :"分为两部分:第一部分是范围内用于迭代的变量,第二部分则表示被迭代的范围,自动迭代,自动取数据,自动判断结束。
范围for可以作用到数组和容器对象上进行遍历
范围for的底层很简单,容器遍历实际就是替换为迭代器,这个从汇编层也可以看到。
cpp
int main()
{
int array[] = { 1, 2, 3, 4, 5 };
// C++98的遍历
for (int i = 0; i < sizeof(array) / sizeof(array[0]); ++i)
{
array[i] *= 2;
}
for (int i = 0; i < sizeof(array) / sizeof(array[0]); ++i)
{
cout << array[i] << endl;
}
// C++11的遍历
for (auto& e : array)
e *= 2;
for (auto e : array)
cout << e << " " << endl;
cout << endl;
return 0;
}
1.string类的常用接口
1.1string类的常见构造

cpp
#include <iostream>
#include <string> // 使用 string 必须包含此头文件
#include <vector>
int main()
{
// ==================== 1. 构造与赋值 ====================
std::cout << "========== 1. 构造与赋值 ==========\n";
std::string s1; // 默认构造,空字符串
std::string s2("Hello C++"); // 从 C 风格字符串构造
std::string s3(s2); // 拷贝构造
std::string s4(5, 'A'); // 构造包含 5 个 'A' 的字符串:"AAAAA"
std::string s5 = "Direct Assign"; // 赋值构造
std::cout << "s1: [" << s1 << "]\n";
std::cout << "s2: " << s2 << "\n";
std::cout << "s3 (copy of s2): " << s3 << "\n";
std::cout << "s4 (5个A): " << s4 << "\n";
std::cout << "s5: " << s5 << "\n\n";
return 0;
}
1.2string类对容量的操作
注意:
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不会改变容量大小。
cpp
// ==================== 2. 大小与容量 ====================
std::cout << "========== 2. 大小与容量 ==========\n";
std::string str = "Hello";
std::cout << "str = " << str << "\n";
std::cout << "size() = " << str.size() << " (字符个数,同 length())\n";
std::cout << "length() = " << str.length() << "\n";
std::cout << "capacity() = " << str.capacity() << " (当前分配的内存容量)\n";
std::cout << "empty() = " << (str.empty() ? "true" : "false") << " (是否为空)\n";
str.resize(10, 'X'); // 调整大小为10,多出的用 'X' 填充
std::cout << "resize(10, 'X') 后: " << str << "\n";
str.reserve(100); // 预留至少100个字符空间(不改变 size)
std::cout << "reserve(100) 后 capacity = " << str.capacity() << "\n\n";
1.3string类的访问

cpp
// ==================== 3. 访问元素 ====================
std::cout << "========== 3. 访问元素 ==========\n";
std::string text = "ABCDE";
std::cout << "text = " << text << "\n";
// 使用 operator[](不检查边界)
std::cout << "text[0] = " << text[0] << "\n";
std::cout << "text[2] = " << text[2] << "\n";
// 使用 at()(检查边界,越界抛异常)
std::cout << "text.at(3) = " << text.at(3) << "\n";
// 访问首尾字符
std::cout << "front() = " << text.front() << "\n";
std::cout << "back() = " << text.back() << "\n";
// 获取底层 C 字符串
const char* cstr = text.c_str();
std::cout << "c_str() = " << cstr << "\n\n";
1.4string类的修改操作

cpp
// ==================== 4. 修改操作 ====================
std::cout << "========== 4. 修改操作 ==========\n";
std::string msg = "Hello";
std::cout << "初始: " << msg << "\n";
// 追加
msg.push_back('!'); // 尾部添加单个字符
std::cout << "push_back('!'): " << msg << "\n";
msg.append(" World"); // 追加字符串
std::cout << "append(\" World\"): " << msg << "\n";
msg += "!!!"; // 运算符重载,更简洁
std::cout << "+= \"!!!\": " << msg << "\n";
// 插入和删除
msg.insert(5, " Beautiful"); // 在位置5插入
std::cout << "insert(5, \" Beautiful\"): " << msg << "\n";
msg.erase(5, 10); // 从位置5开始删除10个字符
std::cout << "erase(5, 10): " << msg << "\n";
// 替换
msg.replace(6, 5, "CPP"); // 从位置6开始替换5个字符为 "CPP"
std::cout << "replace(6, 5, \"CPP\"): " << msg << "\n";
// 清空
msg.clear();
std::cout << "clear() 后: [" << msg << "] (空字符串)\n\n";
1.5string类的查找

cpp
// ==================== 5. 查找与子串 ====================
std::cout << "========== 5. 查找与子串 ==========\n";
std::string sentence = "The quick brown fox jumps over the lazy dog";
std::cout << "句子: " << sentence << "\n";
// 查找子串
size_t pos = sentence.find("fox");
if (pos != std::string::npos) { // npos 是静态常量,表示"未找到"
std::cout << "找到 \"fox\",位置: " << pos << "\n";
}
// 从指定位置开始查找
size_t pos2 = sentence.find("the", 20); // 从位置20开始找
std::cout << "从位置20开始找 \"the\",位置: " << pos2 << "\n";
// 反向查找
size_t pos3 = sentence.rfind("the");
std::cout << "反向查找 \"the\",最后一次出现的位置: " << pos3 << "\n";
// 提取子串
std::string sub = sentence.substr(10, 5); // 从位置10开始取5个字符
std::cout << "substr(10, 5) = " << sub << "\n";
// 查找字符集合(首次出现)
size_t pos4 = sentence.find_first_of("aeiou"); // 找到第一个元音字母
std::cout << "第一个元音字母位置: " << pos4 << ",字符: " << sentence[pos4] << "\n\n";
2.string的模拟实现代码
string.h
cpp
#pragma once
#include<iostream>
#include<assert.h>
#include<algorithm>
namespace Mystring
{
class string
{
public:
//string()
// :_str(new char[1]{'\0'})
// ,_size(0)
// ,_capacity(0)
//{}
typedef char* iterator;
typedef const char* const_iterator;
//迭代器
iterator begin()
{
return _str;
}
iterator end()
{
return _str + _size;
}
const_iterator begin()const
{
return _str;
}
const_iterator end()const
{
return _str + _size;
}
//访问
const char& operator[](size_t pos)const
{
assert(pos < _size);
return _str[pos];
}
//容量
size_t size()const
{
return _size;
}
size_t capacity()const
{
return _capacity;
}
void resize(size_t n, char ch = '\0');
void reserve(size_t n);
void clear()
{
_str[0] = '\0';
_size = 0;
}
bool empty()
{
return _size == 0;
}
const char* c_str()const
{
return _str;
}
void swap(string& s);
//构造
string(const char* str = " ");
~string();
//拷贝构造
string(const string& s);
//赋值重载
string& operator=(const string& s);
//修改
void push_back(char c);
void append(const char* str);
string& operator+=(const char* str)
{
append(str);
return *this;
}
string& operator+=(char ch)
{
push_back(ch);
return *this;
}
void insert(size_t pos,char ch);
void insert(size_t pos, const char* str);
void erase(size_t pos = 0, size_t len = npos);
//查找
size_t find(char ch, size_t pos = 0);
size_t find(const char* str, size_t pos = 0);
string substr(size_t pos = 0, size_t len = npos);
bool operator<(const string& s) const;
bool operator<=(const string& s) const;
bool operator>(const string& s) const;
bool operator>=(const string& s) const;
bool operator==(const string& s) const;
bool operator!=(const string& s) const;
friend std::istream& operator>>(std::istream& in, const string& s);
friend std::ostream& operator<<(std::ostream& out, const string& s);
private:
char* _str;
size_t _size;
size_t _capacity;
public:
//const static整形可以这样 double不支持
const static size_t npos = -1;
};
//类外实现
std::ostream& operator<<(std::ostream& out, const string& s);
std::istream& operator>>(std::istream& in, const string& s);
std::istream& getline(std::istream& is, string& str, char delim = '\n');
}
string.c
cpp
#include"string.h"
namespace Mystring
{
void string::swap(string& s)
{
std::swap(_str, s._str);
std::swap(_size, s._size);
std::swap(_capacity, s._capacity);
}
string::string(const char* str)
:_size(strlen(str))
{
_capacity = _size;
_str = new char[_size];
strcpy(_str, str);
}
string::string(const string& s)
{
_str = new char[s._capacity + 1];
_size = s._size;
_capacity = s._capacity;
memcpy(_str, s._str, s._size + 1);
}
string& string::operator=(const string& s)
{
if(this != &s)
{
char* tmp = new char[s._capacity + 1];
delete[] _str;
_size = s._size;
_capacity = s._capacity;
memcpy(tmp, s._str, s._size + 1);
_str = tmp;
}
return *this;
}
string::~string()
{
delete[] _str;
_str = nullptr;
_size = 0;
_capacity = 0;
}
//容量
void string::resize(size_t n, char ch = '\0')
{
if (_capacity < n)
{
reserve(n);
for (size_t i = _size; i < _capacity; i++)
{
_str[i] = ch;
}
_size = n;
_str[_size] = '\0';
}
else
{
_size = n;
_str[_size] = '\0';
}
}
void string::reserve(size_t n)
{
if (n > _capacity)
{
char* tmp = new char[n + 1];
memcpy(tmp, _str, _size + 1);
delete[] _str;
_str = tmp;
_capacity = n;
}
}
//修改
void string::push_back(char c)
{
if (_size == _capacity)
{
reserve(_capacity == 0 ? 4 : _capacity * 2);
}
_str[_size] = c;
++_size;
_str[_size] = '\0';
}
void string::append(const char* str)
{
size_t len = strlen(str);
if (_size + len > _capacity)
{
reserve(std::max(_size+len,_capacity));
}
memcpy(_str + _size, str, len+1);
_size += len;
}
void string::insert(size_t pos, char ch)
{
//向后移动数据
assert(pos <= _size);
if (_size == _capacity)
{
reserve(_capacity == 0 ? 4 : _capacity * 2);
}
size_t end = _size+1;
while (end > pos)
{
_str[end] = _str[end-1];
end--;
}
_str[pos] = ch;
_size++;
}
void string::insert(size_t pos, const char* str)
{
assert(pos <= _size);
size_t len = strlen(str);
if (_size == _capacity)
{
reserve(std::max(_size+len,_capacity*2));
}
size_t end = _size + len;
while (end-len >pos-1 )
{
_str[end] = _str[end - len];
end--;
}
memcpy(_str + pos, str, len);
_size += len;
}
void string::erase(size_t pos, size_t len )
{
assert(pos < _size);
if (len >= _size - pos || len == npos)
{
//删完了
_size = pos;
_str[_size] = '\0';
}
else
{
memcpy(_str + pos, _str + pos + len, _size - pos - len + 1);
_size -= len;
}
}
//查找
size_t string::find(char ch, size_t pos )
{
assert(pos < _size);
for (size_t i = 0; i < _size; i++)
{
if (_str[i] == ch)
{
return i;
}
}
return npos;
}
size_t string::find(const char* str, size_t pos)
{
assert(pos < _size);
char* tmp = strstr(_str + pos, str);
if (tmp)
{
return tmp - _str;
}
else
{
return npos;
}
}
string string::substr(size_t pos = 0, size_t len)
{
assert(pos < _size);
if (len == npos || _size - pos < len)
{
//pos后全部
len = _size - pos;
}
string sub;
sub.reserve(len);
memcpy(&sub, _str + pos, len);
return sub;
}
bool string::operator<(const string& s) const
{
return strcmp(_str, s._str) < 0;
}
bool string::operator<=(const string& s) const
{
return (*this < s && *this == s);
}
bool string::operator>(const string& s) const
{
return !(*this <= s);
}
bool string::operator>=(const string& s) const
{
return !(*this < s);
}
bool string::operator==(const string& s) const
{
return strcmp(_str, s._str) == 0;
}
bool string::operator!=(const string& s) const
{
return !(*this == s);
}
std::ostream& operator<<(std::ostream& out, const string& s)
{
for (auto ch : s)
{
out << ch;
}
return out;
}
std::istream& operator>>(std::istream& in,string& s)
{
s.clear();
char buff[256];
int i = 0;
char ch;
ch = in.get();
while (ch != '\n' && ch != ' ')
{
buff[i++] = ch;
if (i == 255)
{
buff[i] = '\0';
s += buff;
int i = 0;
}
ch = in.get();
}
if (i > 0)
{
buff[i] = '\0';
s += buff;
}
return in;
}
std::istream& getline(std::istream& in, string& str, char delim )
{
str.clear();
char buff[256];
int i = 0;
char ch;
ch = in.get();
while (ch != delim)
{
buff[i++] = ch;
if (i == 255)
{
buff[i] = '\0';
str += buff;
int i = 0;
}
ch = in.get();
}
if (i > 0)
{
buff[i] = '\0';
str += buff;
}
return in;
}
}
3.string的现代写法
cpp
String(const String& s)
: _str(nullptr)
{
String strTmp(s._str);
swap(_str, strTmp._str);
}
String& operator=(String s)
{
swap(_str, s._str);
return *this;
}