c++

c++ string库函数中替换字符串的方法

小樊
82
2024-09-24 22:21:16
栏目: 编程语言

在C++的<string>库中,你可以使用std::string类的成员函数replace()来替换字符串中的部分内容。

以下是replace()函数的基本语法:

std::string& replace(size_type pos, size_type count, const std::string& str);

参数说明:

返回值:

下面是一个使用replace()函数的示例:

#include <iostream>
#include <string>

int main() {
    std::string s = "Hello, World!";
    std::cout << "Original string: "<< s << std::endl;

    // 替换字符串中的"World"为"C++"
    s.replace(7, 5, "C++");
    std::cout << "Modified string: "<< s << std::endl;

    return 0;
}

输出:

Original string: Hello, World!
Modified string: Hello, C++!

在这个示例中,我们首先创建了一个包含"Hello, World!“的字符串s。然后,我们使用replace()函数将字符串中的"World"替换为"C++”,并输出修改后的字符串。

0
看了该问题的人还看了