std::string 将某个子串删掉
时间: 2023-09-10 20:07:17 浏览: 99
好的,关于你的问题,可以通过以下代码进行处理:
```c++
#include <string>
using namespace std;
void deleteSubstring(string& str, const string& sub) {
int pos = str.find(sub);
while (pos != string::npos) {
str.erase(pos, sub.length());
pos = str.find(sub);
}
}
```
其中,`str` 为要处理的字符串,`sub` 为要删除的子串。函数会遍历字符串中所有的子串,将其删去。
相关问题
std::string 使用
std::string 是 C++ 中的一种字符串类型。它实际上是一个封装了动态字符数组的类。使用 std::string 可以轻松地进行字符串操作,如拼接、插入、删除、查找等。
使用 std::string 的方法如下:
1. 定义 std::string 变量:
```
#include <string>
std::string s; // 空字符串
std::string s1 = "Hello, world!"; // 使用字面值初始化
std::string s2(s1); // 使用另一个 std::string 初始化
std::string s3(5, 'a'); // 使用重复的字符初始化
```
2. 使用 std::string:
```
std::string s1 = "Hello, ";
std::string s2 = "world!";
std::string s3 = s1 + s2; // 使用 + 运算符拼接字符串
s1 += s2; // 使用 += 运算符拼接字符串
s1.size(); // 获取字符串的长度
s1.empty(); // 判断字符串是否为空
s1[0] = 'H'; // 修改字符串的某个位置的值
s1.find(s2); // 查找字符串中的子串
s1.substr(0, 5); // 获取字符串的子串
s1.insert(5, s2); // 在字符串的某个位置插入子串
s1.erase(5, 5); // 从字符串的某个位置开始删除子串
```
std::string 也有许多其他的方法,更多详细信息可以参考 C++ 官方文档。
std::string
`std::string` 是 C++ 标准库中的一个字符串类,使用该类可以方便的进行字符串的操作,如拼接、查找、替换等。
`std::string` 类的头文件为 `<string>`。在使用时,需要包含该头文件,并使用 `using namespace std;`,或者显式地使用 `std::string`。
下面是一些常用的 `std::string` 操作:
1. 创建字符串
```c++
std::string str("hello");
```
2. 访问字符串
```c++
char ch = str[0]; // 访问第一个字符
std::cout << str << std::endl; // 输出字符串
```
3. 拼接字符串
```c++
std::string str1 = "hello";
std::string str2 = "world";
std::string str3 = str1 + " " + str2; // 拼接字符串
```
4. 查找字符串
```c++
std::string str = "hello world";
int pos = str.find("world"); // 查找子串的位置
```
5. 替换字符串
```c++
std::string str = "hello world";
str.replace(0, 5, "hi"); // 将前 5 个字符替换为 "hi"
```
6. 插入字符串
```c++
std::string str = "hello world";
str.insert(5, "cruel "); // 在第 5 个字符处插入字符串
```
7. 删除字符串
```c++
std::string str = "hello world";
str.erase(5, 6); // 从第 5 个字符开始删除 6 个字符
```
以上是一些常用的 `std::string` 操作,更多使用方法可参考官方文档。
相关推荐
![application/x-zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.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)
![](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)
![](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)