跳到主要内容

9. strings (字符串)

定义字符串类型和相关操作。头文件: <string>。

9.1 basic_string​


template <class charT, class traits = char_traits<charT>, class Allocator = allocator<charT>> class basic_string

可变字符串类。

  • 输入: charT — 字符类型; traits — 字符特性; Allocator — 分配器
  • 输出: 字符串对象
  • 注意: 类似 vector 的连续存储

basic_string()

默认构造。

  • 输入: 无
  • 输出: 空字符串

basic_string(const value_type* s)

从 C 字符串构造。

  • 输入: s
  • 输出: 字符串对象

basic_string& operator+=(const basic_string& str)

追加字符串。

  • 输入: str
  • 输出: *this

void push_back(value_type c)

尾部添加字符。

  • 输入: c
  • 输出: void

void pop_back()

尾部移除字符。

  • 输入: 无
  • 输出: void
  • 注意: C++11

basic_string substr(size_type pos = 0, size_type n = npos) const

获取子串。

  • 输入: pos, n
  • 输出: 新字符串

const value_type* c_str() const noexcept

获取 C 字符串。

  • 输入: 无
  • 输出: const char* — 保证以 null 结尾

size_type find(const basic_string& str, size_type pos = 0) const noexcept

查找子串。

  • 输入: str, pos
  • 输出: size_type — 位置或 npos

size_type rfind(...)

反向查找。

  • 输入: 同 find
  • 输出: size_type

int compare(...)

比较。

  • 输入: 多种形式
  • 输出: int