[关闭]
@rg070836rg 2015-08-16T15:10:52.000000Z 字数 2165 阅读 1547

【string字符串操作】

data_structure

一、比较字符串

允许的比较对象

  • 1)compare(s2) 其他同类型字符串
  • 2)compare(p) C 风格字符串
  • 3)compare(off, cnt, s2) [off, off + cnt) 同 s2 执行比较
  • 4)compare(off, cnt, s2, off2, cnt2) [off, off + cnt) 同 s2 [off2, cnt2) 执行比较
  • 5)compare(off, cnt, p) [off, off + cnt) 同 [p , ) 执行比较
  • 6)compare(off, cnt, p, cnt2) [off, off + cnt) 同 [p, p + cnt2) 执行比较
    返回 -1, 0, 1 作为小于、等于和大于的比较结果。

二、附加数据

1)使用 operator += 接受其他字符串,C 风格字符串和字符

2)使用 push_back() 在尾部附加字符,并使得通过字符串构造的 back_iterator 可以访问

3)append() 附加

  • 1、append(s) 追加字符串
  • 2、append(s, off, cnt) 追加字符串 s [off, off + cnt)
  • 3、append(p) 追加字符串 [p, )
  • 4、append(p, cnt) 追加字符串 [p, p + cnt)
  • 5、append(n, c) 填充 n * c
  • 6、append(InF, InL) 追加输入流 [InF, InL)

4)insert() 插入

  • 1、insert(off, s2) 插入字符串
  • 2、insert(off, s2, off2, cnt2) 插入字符串 s [off2, off2 + cnt2)
  • 3、insert(off, p) 插入字符串 [p, )
  • 4、insert(off, p, cnt) 插入字符串 [p, p + cnt)
  • 5、insert(off, n, c) 插入 n * c
  • 6、insert(iter) 元素默认值填充
  • 7、insert(iter, c) 插入特定元素
  • 8、insert(iter, n, c) 插入 n*c
  • 9、insert(iter, InF, InL) 插入 [InF, InL)

5)operator +(a, b)

字符串关联运算符重载中支持 operator + 的形式

  • 1、s + s
  • 2、s + p
  • 3、s + c
  • 4、p + s
  • 5、c + s

三、查找、替换和清除

1)find() 查找

  • 1、find(c, off) 在 s [off, npos) 中查找 c
  • 2、find(p, off, n) 在 s [off, npos) 中查找 [p, p + n)
  • 3、find(p, off) 在 s [off, npos) 中查找 [p, )
  • 4、find(s2, off) 在 s [off, npos) 中查找 s2

2)find() 的变种

  • 1、rfind() 具有 find() 的输入形式,反序查找
  • 2、find_first_of() 具有 find() 的输入形式,返回第一个匹配的索引
  • 3、find_last_of() 具有 find() 的输入形式,返回倒数第一个匹配的索引
  • 4、find_first_not_of() 具有 find() 的输入形式,返回第一个不匹配的索引
  • 5、find_last_not_of() 具有 find() 的输入形式,返回倒数第一个不匹配的索引

3)replace() 替换

  • 1、replace(off, cnt, s2) 将 s [off, off + cnt) 替换成 s2
  • 2、replace(off, cnt, s2, off2, cnt2) 将 s [off, off + cnt) 替换成 s2 [off2, off2 + cnt2)
  • 3、replace(off, cnt, p) 将 s [off, off + cnt) 替换成 [p, )
  • 4、replace(off, cnt, p, cnt2) 将 s [off, off + cnt) 替换成 [p, p + cnt2)
  • 5、replace(off, cnt, n, c) 将 s [off, off + cnt) 替换成 c * n
    使用迭代器的情况:
  • 6、replace(InF, InL, s2) 将 [InF, InL) 替换成 s2
  • 7、replace(InF, InL, p) 将 [InF, InL) 替换成 [p, )
  • 8、replace(InF, InL, p, cnt) 将 [InF, InL) 替换成 [p, p + cnt)
  • 9、replace(InF, InL, n, c) 将 [InF, InL) 替换成 n * c
  • 10、replace(InF, InL, InF2, InL2) 将 [InF, InL) 替换成 [InF2, InL2)

4)erase() 删除

  • 1、erase(off, cnt) 从字符串 s 中删除 s [off, off + cnt)
  • 2、erase(iter) 从字符串 s 中删除 *iter
  • 3、erase(ItF, ItL) 从字符串 s 中删除 [ItF, ItL)

四、取出字符串

1)取得 C 风格字符串

c_str() 返回常量类型的 C 风格字符串指针,copy(ptr, cnt, off = 0) 则将指定大小的字符串复制到特定指针。data() 在 Visual C++ 7.1 中仅仅调用了 c_str() 实现。

2)取得子字符串

substr(off, cnt) 取得 s [off, off + cnt) 的副本。

3)复制子字符串

copy(p, off, cnt) 将 s [off, off + cnt) 复制到 p。


五、字符串的缓冲区管理

字符串具有类似 std::vector 的缓冲区管理界面。

  • size() 取得有效元素长度
  • max_size() 取得当前内存分配器能分配的有效空间
  • reserve() 为缓冲区预留空间
  • capacity() 取得缓冲区的容量
  • resize() 重设串的长度,可以为其指定初始化值
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注