mobile wallpaper 1
mobile wallpaper 2
mobile wallpaper 3
mobile wallpaper 4
371 words
1 minute
string容器 - CPP STL
2026-10-08
2 HX2O ⟶点燃 2 HX2+OX2\ce{2H2O \overset{\text{点燃}}{\longrightarrow} 2H2 + O2}

string基本概念#

本质:#

string是C++风格的字符串,而string本质上是一个类

string和char*区别:#

char* 是一个指针

string是一个类,类内部封装了char*,管理这个字符串,是一个char*型容器

特点:

string类内部封装了很多成员方法

例如:查找 find, 拷贝 copy, 删除 delete , 替换 replace, 插入 insert

string管理char*所分配的内存,不用担心复制越界和取值越界等,由类内部进行负责

string赋值操作#

功能描述:#

​ 给string字符串进行赋值

赋值的函数原型:#

string& operator=(const char* s); //char*类型字符串 赋值给当前的字符串
string& operator=(const string& s); //把字符串s赋值给当前字符串
string& operator=(char c); //字符赋值给当前的字符串
string& assign(const char* s); //把字符串s赋给当前的字符串
string& assign(const char*s,int n); //把字符串s的前n个字符赋值给当前字符串
string& assign(const string &s); //把字符串s赋值给当前字符
string& assign(int n,char c); //用n个字符c赋值给字符串

string字符串拼接#

功能描述:#

  • 实现在字符串末尾拼接字符串

函数原型:#

string& operator+=(const char* str); //重载+=
string& operator+=(const char c);
string& operator+=(const string& str);
string& append(const char* s); //把字符串s连接到当前字符串结尾
string& append(const char *s,int n); //把字符串s的前n个字符链接到当前字符串结尾
string& append(const string& s); //同operator+=(const string& str)
string& append(const string& s,int pos,int n); //字符串s中从pos开始的n个字符连接到字符串结尾

string查找和替换#

功能描述:#

  • 查找:查找指定字符串是否存在
  • 替换:在指定的位置替换字符串

函数原型:#

int find(const string& str,int pos = 0) const; //查找str第一次出现位置,从pos开始查找
int find(const char* s,int pos = 0) const; //查找s第一次出现的位置,从pos开始查找
int find(const char* s,int pos ,int n) const; //从pos位置查找s的前n个字符第一次位置
int find(const char c,int pos = 0) const; //查找c第一次出现的位置
int rfind(const string& str,int pos = npos) const; //查找str最后一次位置,从pos开始查找
int rfind(const char* s ,int pos = npos) const; //查找s最后依次位置,从pos开始
int rfind(const char* s ,int pos ,int n) const; //从pos查找s的前n个字符最后一次位置
int rfind(const char* s ,int pos = 0) const; //查找字符c最后一次位置
string& replace(int pos ,int n,const string& str); //替换从pos开始n个字符为字符串str
string& replace(int pos ,int n ,const char* s);//替换从pos开始的n个字符为字符串s

string字符串比较#

功能描述:#

  • 字符串之间的比较

比较方式:#

  • 字符串比较是按字符串的ASCII码比较的
  • = 返回 0
  • > 返回 1
  • < 返回 -1

函数原型:#

int compare(const string& str) const ; //与字符串str比较
int compare(const char* s) const; //与字符串s比较

string字符存取#

string中单个字符存取有2种

char& operator[](int n); //通过中括号方式取字符
char& at(int n); //通过at方式取字符

string插入和删除#

功能描述:#

  • 对string字符串进行插入和删除字符操作

函数原型:#

string& insert(int pos,const char* s);//插入字符串
string& insert(int pos,const string& str); //插入字符串
string& insert(int pos,int n,char c); //在指定位置插入n个字符c
string& erase(int pos,int n = npos); //删除从pos开始的n个字符串

string子串#

功能描述:#

  • 从字符串种获取想要的子串

函数原型:#

string substr(int pos = 0 , int n = npos) const; //返回由pos开始的n个字符组成的字符串

Video#

Share

If this article helped you, please share it with others!

string容器 - CPP STL
https://www.bilibili.com/video/BV1et411b73Z/?p=189
Author
Memki
Published at
2026-10-08
License
CC BY-NC-SA 4.0

Some information may be outdated

Table of Contents