c++ string 删除指定位置字符 函数
时间: 2024-11-15 07:32:53 浏览: 99
在C++中,如果你想要删除`std::string`中的某个指定位置的字符,可以使用`substr()`函数结合`erase()`函数。但是直接通过索引修改`std::string`的元素是不可行的,因为它是只读的。下面是一个示例:
```cpp
#include <iostream>
#include <string>
void delete_char_at(std::string& str, size_t pos) {
// 如果位置越界,不作处理
if (pos >= str.size()) return;
// 使用 substr 创建从开始到pos前的一个新字符串,然后用 erase 删除原始字符串的对应部分
str.erase(0, pos);
}
int main() {
std::string my_string = "Hello, World!";
size_t position_to_remove = 7; // 要删除的字符的位置
delete_char_at(my_string, position_to_remove);
std::cout << "Modified string after deletion: " << my_string << std::endl;
return 0;
}
```
运行这段代码后,`my_string`将变为"Hello, World!",其中第8个字符("W")已被删除。
阅读全文
相关推荐

















