c++ replace函数如何使用

655Z技术栈 C/C++编程 8小时前 2

在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++!"。

提供PHP及ThinkPHP框架的定制开发、代码优化,PHP修改、ThinkPHP修改。

邮箱:yvsm@163.com 微信:yvsm316 QQ:316430983
关闭

用微信“扫一扫”