21xrx.com
2024-09-20 00:33:20 Friday
登录
文章检索 我的文章 写文章
C++中的replace函数使用方法和示例
2023-07-02 12:22:43 深夜i     --     --
C++ Replace函数 使用方法 示例 字符串替换

C++是一门流行的编程语言,其拥有众多强大的函数,其中replace函数用于将字符串中的特定字符替换为新的字符或字符串。本文将介绍replace函数的使用方法和示例。

replace函数属于string库,其使用格式如下:


string& replace(pos1, n1, str);

string& replace(iterator i1, iterator i2, str);

string& replace(pos1, n1, str, pos2, n2);

string& replace(pos1, n1, const char* s);

string& replace(iterator i1, iterator i2, const char* s);

string& replace(pos1, n1, const char* s, n2);

string& replace(pos1, n1, size_t n2, char c);

其中,pos1表示起始位置,n1表示要替换的字符个数,str表示替换后的字符或字符串,i1和i2为替换区间,pos2为替换区间内起始位置,n2为替换区间中要替换的字符个数,s为替换后的字符串,c为替换后的字符。

下面是使用replace函数的示例:


#include <iostream>

#include <string>

using namespace std;

int main()

{

  string str = "hello world";

  str.replace(0, 5, "hi");

  cout << str << endl; // 输出:hi world

  str = "apple is delicious";

  str.replace(0, 5, "orange");

  cout << str << endl; // 输出:orange is delicious

  str = "hello world";

  str.replace(str.begin(), str.begin() + 5, "hi");

  cout << str << endl; // 输出:hi world

  str = "apple is delicious";

  str.replace(str.begin(), str.begin() + 5, "orange");

  cout << str << endl; // 输出:orange is delicious

  str = "hello world";

  str.replace(0, 5, "hi", 0, 2);

  cout << str << endl; // 输出:hi world

  str = "apple is delicious";

  str.replace(0, 5, "orange", 0, 6);

  cout << str << endl; // 输出:orange is delicious

  str = "hello world";

  str.replace(0, 5, "hi");

  cout << str << endl; // 输出:hi world

  str = "apple is delicious";

  str.replace(0, 5, "orange");

  cout << str << endl; // 输出:orange is delicious

  str = "hello world";

  str.replace(str.begin(), str.begin() + 5, "hi");

  cout << str << endl; // 输出:hi world

  str = "apple is delicious";

  str.replace(str.begin(), str.begin() + 5, "orange");

  cout << str << endl; // 输出:orange is delicious

  str = "hello world";

  str.replace(0, 5, "hi", 0, 2);

  cout << str << endl; // 输出:hi world

  str = "apple is delicious";

  str.replace(0, 5, "orange", 0, 6);

  cout << str << endl; // 输出:orange is delicious

  str = "hello world";

  str.replace(0, 5, "hi", 2);

  cout << str << endl; // 输出:hillo world

  str = "apple is delicious";

  str.replace(0, 5, "orange", 3);

  cout << str << endl; // 输出:orenge is delicious

  str = "hello world";

  str.replace(0, 5, 2, 'h');

  cout << str << endl; // 输出:hhhhh world

  str = "apple is delicious";

  str.replace(0, 5, 3, 'o');

  cout << str << endl; // 输出:oooooe is delicious

  return 0;

}

总之,replace函数是C++中十分常用的函数之一,应用范围广泛。掌握其使用方法和技巧对于C++编程者而言是非常有必要的。

  
  

评论区

{{item['qq_nickname']}}
()
回复
回复