string容器中erase的使用
时间: 2023-10-10 07:15:52 浏览: 124
在C++中,string是一个容器类,用于存储和操作字符串。erase()是string类中的一个成员函数,用于从字符串中删除字符或子串。
erase()函数有多个重载形式,下面是其中两个常用的形式:
1. erase(pos, count):从指定位置开始删除指定数量的字符。
- pos:要删除的起始位置,索引从0开始。
- count:要删除的字符数量。
2. erase(iterator):从字符串中删除指定位置的字符。
- iterator:指向要删除字符位置的迭代器。
以下是使用erase()函数的示例代码:
```cpp
#include <iostream>
#include <string>
int main() {
std::string str = "Hello, World!";
// 删除字符串中的逗号和空格
str.erase(std::remove(str.begin(), str.end(), ','), str.end());
str.erase(std::remove(str.begin(), str.end(), ' '), str.end());
std::cout << str << std::endl; // 输出:HelloWorld!
// 删除字符串中的"World"
size_t pos = str.find("World");
if (pos != std::string::npos) {
str.erase(pos, 5); // 5是"World"的长度
}
std::cout << str << std::endl; // 输出:Hello!
return 0;
}
```
上述代码中,首先使用erase()和remove()函数结合,删除字符串中的逗号和空格。然后使用find()函数找到"World"在字符串中的位置,再使用erase()函数删除该子串。
希望这个例子能帮助你理解string容器中erase()函数的使用。如有疑问,请随时提问!
阅读全文
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![docx](https://img-home.csdnimg.cn/images/20241231044901.png)
![-](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20241231044833.png)
![-](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)