std::string 实现字符串 replace
时间: 2023-11-15 14:04:30 浏览: 62
可以使用 C++ 的标准库中的 `std::string` 类来实现字符串替换。`std::string` 类提供了 `replace` 方法,可以用来替换指定位置的字符串。
示例代码如下:
```c++
#include <iostream>
#include <string>
int main() {
std::string str = "hello world";
std::cout << "原始字符串: " << str << std::endl;
// 将 "world" 替换为 "C++"
str.replace(str.find("world"), 5, "C++");
std::cout << "替换后的字符串: " << str << std::endl;
return 0;
}
```
输出结果为:
```
原始字符串: hello world
替换后的字符串: hello C++
```
在代码中,我们使用 `find` 方法找到字符串中 "world" 的位置,然后使用 `replace` 方法将其替换为 "C++"。其中,第一个参数指定要替换的字符串的起始位置,第二个参数指定要替换的字符串的长度,第三个参数指定用来替换的字符串。
相关问题
std::string 实现字符串 replace 函数
可以使用 string::find 和 string::replace 函数来实现字符串 replace 函数,以下是一个示例实现:
```c++
#include <iostream>
#include <string>
void replaceAll(std::string& str, const std::string& oldStr, const std::string& newStr) {
size_t pos = 0;
while ((pos = str.find(oldStr, pos)) != std::string::npos) {
str.replace(pos, oldStr.length(), newStr);
pos += newStr.length();
}
}
int main() {
std::string str = "Hello, World!";
std::cout << "Original string: " << str << std::endl;
replaceAll(str, "World", "John Doe");
std::cout << "Replaced string: " << str << std::endl;
return 0;
}
```
输出:
```
Original string: Hello, World!
Replaced string: Hello, John Doe!
```
该示例中,replaceAll 函数接受三个参数:一个要修改的字符串,一个要替换的子字符串和一个新的子字符串。它使用 string::find 函数来查找要替换的子字符串的位置,并使用 string::replace 函数将其替换为新的子字符串。另外,由于 string::replace 函数会改变原始字符串的长度,因此在每次替换后需要将查找位置增加新子字符串的长度。
std::string replace 替换字符串
std::string的replace函数可以用于替换字符串中的子串。它的函数签名如下:
```cpp
std::string& replace(size_t pos, size_t count, const std::string& str);
```
其中,pos表示要替换的起始位置,count表示要替换的字符数,str表示用于替换的字符串。
replace函数会将原字符串中从pos位置开始的count个字符替换为str。如果str的长度小于count,则只会替换掉count个字符;如果str的长度大于count,则会替换掉count个字符,并在pos位置插入str中多出来的字符。
下面是一个示例代码:
```cpp
#include <iostream>
#include <string>
int main() {
std::string str = "Hello, world!";
std::cout << "原始字符串:" << str << std::endl;
str.replace(7, 5, "C++");
std::cout << "替换后的字符串:" << str << std::endl;
return 0;
}
```
输出结果为:
```
原始字符串:Hello, world!
替换后的字符串:Hello, C++!
```