c++ string删除指定字符
时间: 2023-12-07 07:00:42 浏览: 83
在 C++ 中,可以使用 `erase` 方法来删除一个字符串中的指定字符。具体操作步骤如下:
1. 使用 `find` 方法查找字符串中要删除的字符的位置。
2. 如果找到了要删除的字符,则使用 `erase` 方法删除该字符。
下面是一个示例代码:
```c++
#include <iostream>
#include <string>
using namespace std;
int main() {
string str = "Hello, world!";
char ch = 'o';
// 查找要删除的字符
size_t pos = str.find(ch);
// 如果找到了要删除的字符
while (pos != string::npos) {
// 删除该字符
str.erase(pos, 1);
// 继续查找下一个要删除的字符
pos = str.find(ch);
}
cout << str << endl;
return 0;
}
```
以上代码输出结果为:`Hell, wrld!`。
相关问题
c++string删除指定字符
在 C++ 中,可以使用字符串操作函数和算法来删除指定字符。以下是一种常见的方法:
```cpp
#include <iostream>
#include <string>
#include <algorithm>
int main() {
std::string str = "Hello World";
char ch = 'o';
str.erase(std::remove(str.begin(), str.end(), ch), str.end());
std::cout << str << std::endl;
return 0;
}
```
在上面的示例中,我们使用了 `erase` 函数和 `remove` 算法来删除指定字符。首先,我们定义了一个字符串 `str` 和一个字符 `ch`,然后使用 `remove` 函数将要删除的字符移动到字符串的末尾,然后使用 `erase` 函数将末尾的字符删除。最后,我们输出修改后的字符串。
请注意,这种方法只能删除单个字符,并且它会修改原始字符串。如果需要删除多个字符或者不想修改原始字符串,可以使用其他方法,如创建一个新的字符串来保存删除后的结果。
C++ string 替换指定字符串
你可以使用C++中的string类提供的replace函数来替换指定字符串。replace函数的参数是替换起始位置、替换长度和替换内容。以下是一个简单的示例代码:
```c++
#include <string>
#include <iostream>
using namespace std;
int main() {
string s = "Hello world!";
string old_str = "world";
string new_str = "C++";
size_t pos = s.find(old_str);
if(pos != string::npos) {
s.replace(pos, old_str.length(), new_str);
}
cout << s << endl; // 输出:Hello C++!
return 0;
}
```
在这个示例代码中,我们首先使用find函数找到要替换的字符串的起始位置。如果找到了要替换的字符串,就使用replace函数进行替换。最后输出替换后的字符串。需要注意的是,如果要替换的字符串在原字符串中出现多次,上述代码只会替换第一次出现的字符串。