温馨提示×

c++ replace函数如何使用

c++
小樊
82
2024-06-25 16:11:27
栏目: 编程语言

在C++中,我们可以使用replace函数来替换字符串中的指定子串。replace函数的语法如下:

string replace (size_t pos, size_t len, const string& str);

其中,pos表示要替换的子串的起始位置,len表示要替换的子串的长度,str表示替换后的新子串。

下面是一个示例程序,演示如何使用replace函数来替换字符串中的指定子串:

#include <iostream>
#include <string>

int main() {
    std::string str = "Hello World!";
    
    // 替换从位置6开始的5个字符(即"World")
    str.replace(6, 5, "C++");
    
    std::cout << str << std::endl;  // 输出:Hello C++!
    
    return 0;
}

在上面的示例中,我们将字符串"Hello World!“中的"World"替换为"C++”,最终输出结果为"Hello C++!"。

0