输入两个字符串,从第一字符串中删除第二个字符串中所有的字符。例如,输入"They are studer之后的第一个字符串变成”Thy r stdnts.”。用C++
时间: 2023-11-27 18:40:11 浏览: 47
以下是一个用 C++ 编写的函数,可以实现从第一个字符串中删除第二个字符串中所有的字符:
```cpp
#include <iostream>
#include <string>
void removeChars(std::string& str, const std::string& charsToRemove) {
for (const char& c : charsToRemove) {
size_t pos = str.find(c);
while (pos != std::string::npos) {
str.erase(pos, 1);
pos = str.find(c);
}
}
}
int main() {
std::string str1 = "They are studer";
std::string str2 = "之后的第一个字符串变成";
removeChars(str1, str2);
std::cout << "Result: " << str1 << std::endl;
return 0;
}
```
这个函数接受两个参数,第一个参数是要进行删除操作的字符串,第二个参数是要删除的字符集合。函数使用 `std::string` 的 `find` 函数来查找要删除的字符在第一个字符串中的位置,并使用 `std::string` 的 `erase` 函数来删除字符。在循环中,我们会一直查找并删除所有的字符,直到找不到为止。最后,打印出结果字符串。
请注意,这个函数会修改原始的第一个字符串,因此在调用之前请确保备份原始字符串或者使用副本。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)