STL 之 string类

1.比较

    compare()

    例子:

    string A("aBC"), B("ABC");

    A.compare(B); 如果A>B返回1,=返回0,小于返回-1

2.插入

    push_back() 在字符串尾插一个字符

    insert(pos, char); 在确定的位置pos前插入char

3.删除

    函数定义:iterator erase(iterator p); 删除字符串中p所指的字符

              iterator erase(iterator first, iterator last);  删除字符串中迭代器区间[first, last)上所有字符

              string& erase(size_t pos = 0, size_t len = npos); 删除字符串中从索引位置pos开始的len个字符

              void clear(); 删除字符串中所有字符  

4.字符替换

        string& replace(size_t pos, size_t n, const char *s); 将当前字符串从pos开始的n个字符,替换成字符串s

        string& replace(size_t pos, size_t n, size_t n1, char c); 将当前字符串从pos开始的n个字符,替换成n1个字符c

        string& replace(iterator i1, iterator i2, const char *s); 将当前字符串[i1, i2)区间中的字符串替换为字符串s

5.查找 find

        size_t find(constchar *s, size_t pos = 0) const; 在当前字符串的pos索引位置开始,查找字串s,返回找到的位置索引,-1表示查找不到字串

        size_t find(charc, size_t pos = 0) const; 在当前字符串的pos索引位置开始,查找字符c,返回找到的位置索引,找不到返回-1

6.截取字串 substr

        str.substr(pos, n); 从下标为pos开始(包含pos)截取长度为n的字符串

C++ STL中的string是用于处理字符串的容器,提供了丰富的功能和操作方法。 ### string的定义方式 定义string对象时,可采用不同的方式。 ### string的插入 能够向string对象中插入字符或子串。 ### string的拼接 可将多个字符串连接在一起。 ### string的删除 可以从string对象中移除指定位置或范围的字符。 ### string的查找 提供了多种查找方法,如`find()`和`rfind()`: - `size_t find (const char* s, size_t pos = 0) const`:在当前字符串的`pos`索引位置开始,查找子串`s`,返回找到的位置索引, -1表示查找不到子串。 - `size_t find (char c, size_t pos = 0) const`:在当前字符串的`pos`索引位置开始,查找字符`c`,返回找到的位置索引, -1表示查找不到字符。 - `size_t rfind (const char* s, size_t pos = npos) const`:在当前字符串的`pos`索引位置开始,反向查找子串`s`,返回找到的位置索引, -1表示查找不到子串。 - `size_t rfind (char c, size_t pos = npos) const`:在当前字符串的`pos`索引位置开始,反向查找字符`c`,返回找到的位置索引, -1表示查找不到字符 [^3]。 ### string的比较 可以对两个字符串进行比较操作。 ### string的替换 能将指定位置的字符或子串替换为其他内容。 ### string的交换 可交换两个string对象的内容。 ### string的大小和容量 可以获取string对象的大小和容量信息。 ### string中元素的访问 能够访问string对象中的单个字符。 ### string中运算符的使用 支持多种运算符,如`+`用于拼接,`==`用于比较等。 ### string中与迭代器相关的函数 提供了迭代器,方便对string对象进行遍历操作。 ### string与字符串之间的转换 可以在string对象和C风格字符串之间进行转换。 ### string中子字符串的提取 使用`substr()`方法可提取子字符串,例如`string suffix = file.substr(pos);` 可以从指定位置开始提取子串 [^3]。 ### string中的getline函数 用于从输入流中读取一行字符串。 以下是一个简单的示例代码,展示了部分string的操作: ```cpp #include <iostream> #include <algorithm> #include <string> using namespace std; int main() { string s = "ABCDEFG"; // 转换为小写 transform(s.begin(), s.end(), s.begin(), ::tolower); cout << s << endl; string file("stl.cpp"); size_t pos = file.rfind("."); string suffix = file.substr(pos); cout << "File suffix: " << suffix << endl; return 0; } ```
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值