c++

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

小樊
397
2024-09-24 22:21:16
栏目: 编程语言
C++开发者专用服务器,限时0元免费领! 查看>>

在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++”,并输出修改后的字符串。

亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>

相关推荐:c++ string库函数中字符串转数字的方法

0
看了该问题的人还看了