C++ String replace()

2024 年 8 月 30 日 | 阅读 2 分钟

此函数替换字符串中从字符位置 pos 开始并跨 len 个字符的部分。

语法

考虑两个字符串 str1 和 str2。语法如下:

参数

  • str : str 是一个字符串对象,其值将被复制到另一个字符串对象中。
  • pos : pos 定义要替换的字符位置。
  • len : 要被另一个字符串对象替换的字符数。
  • subpos : 它定义要复制到另一个对象作为替换的字符串对象的第一个字符的位置。
  • sublen : 要复制到另一个字符串对象的字符串对象的字符数。
  • n : 要复制到另一个字符串对象的字符数。

返回值

此函数不返回任何值。

示例 1

第一个示例展示了如何使用位置和长度作为参数来替换给定字符串。

输出

Before replacement , string is This is C language
After replacement, string is This is C++ language

示例 2

第二个示例展示了如何使用要复制到另一个字符串对象的字符串的位置和长度来替换给定字符串。

输出

Before replacement, String is This is C language
After replacement, String is This is java language

示例 3

第三个示例展示了如何使用字符串和要复制的字符数作为参数来替换字符串。

输出

Before replacement,string is This is C language
After replacement,string is This is C# language

下一主题C++ 字符串