C++常用的string操作

9

C++常用的string操作

constructors

default (1) string();
copy (2) string (const string& str);
substring (3) string (const string& str, size_t pos, size_t len = npos);
from c-string (4) string (const char* s);
from sequence (5) string (const char* s, size_t n);
fill (6) string (size_t n, char c);
range (7) template string (InputIterator first, InputIterator last);

iterators

  • begin end
  • rbegin rend 反向迭代器
    tips: 前面加 c 就是只读迭代器

Capacity

  • size length
  • max_size 系统限制最大长度
  • resize 调整长度
  • capacity 容量
  • reserve 保留容量
  • clear 清空
  • empty -> bool 是否为空

Element Access

  • operator [] 无越界检查
  • at 有越界检查,超出即抛出错误
  • back 最后一个字符
  • front 第一个字符

Modifiers

  • operator +=
  • append
  • push_back
  • assign
  • insert
  • erase
  • replace
  • swap
  • pop_back

String Operations

  • c_str 如其名,返回 const char *
  • data 返回 const char *,注意避坑的是最后不一定有 0 字符!
  • copy 到另一个 char*,参数为 char* s, size_t len, size_t pos = 0
  • find rfind find_first_of find_last_of find_first_not_of find_last_not_of 都差不多啦,接受 c-str, string, char 可以增加参数 pos
  • substr size_t pos = 0, size_t len = npos
  • compare [pos],[len],str,[subpos],[sublen] 前两个参数是对自己来说的,后两个参数是对传进来的 str 说的,后两个参数在的话前两个参数也要在