21xrx.com
2024-09-19 09:12:03 Thursday
登录
文章检索 我的文章 写文章
C++字符串查找替换方法详解
2023-06-26 03:08:06 深夜i     --     --
C++ 字符串 查找 替换 方法

C++是一种常用的编程语言,支持字符串操作,而在字符串操作中,查找和替换是非常常见的任务。下面我们来详细介绍C++中的字符串查找替换方法。

一、C++中字符串查找方法

1、find()

C++中最常用的字符串查找函数是find()函数。它的基本语法如下:

int find(const char* str, int pos) const;

其中,str表示要查找的字符串,pos表示从哪里开始查找,默认为0。函数返回查找到的第一个字符在字符串中的位置,如果未查找到则返回-1。

例如:

string str = "hello world";

int pos = str.find("o");

cout << pos << endl; // 输出结果为4

find()函数还可以指定查找的长度,语法如下:

int find(const char* str, int pos, int n) const;

其中,n表示要查找的长度。例如:

string str = "hello world";

int pos = str.find("l", 5, 1);

cout << pos << endl; // 输出结果为9

2、rfind()

rfind()函数与find()函数类似,不同之处在于它是从字符串的末尾开始查找,返回查找到的最后一个字符在字符串中的位置,如果未查找到则返回-1。

例如:

string str = "hello world";

int pos = str.rfind("o");

cout << pos << endl; // 输出结果为7

3、find_first_of()

C++中的find_first_of()函数用于查找字符串中第一次出现的任意字符。其基本语法如下:

int find_first_of(const char* str, int pos) const;

其中,str表示要查找的字符集合,pos表示从哪里开始查找。函数返回查找到的第一个字符在字符串中的位置,如果未查找到则返回-1。

例如:

string str = "hello world";

int pos = str.find_first_of("ol");

cout << pos << endl; // 输出结果为2

find_first_of()函数还可以指定查找的长度,语法如下:

int find_first_of(const char* str, int pos, int n) const;

其中,n表示要查找的长度。例如:

string str = "hello world";

int pos = str.find_first_of("ol", 4, 4);

cout << pos << endl; // 输出结果为7

二、C++中字符串替换方法

1、replace()

C++中最常用的字符串替换函数是replace()函数。其基本语法如下:

basic_string& replace(size_type pos1, size_type n1, const basic_string& str);

其中,pos1表示要替换的起始位置,n1表示要替换的长度,str表示替换后的字符串。例如:

string str = "hello world";

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

cout << str << endl; // 输出结果为"hi world"

2、erase()和insert()

C++中还可以通过erase()和insert()函数来实现字符串的替换。erase()函数用于删除子字符串,其基本语法如下:

basic_string& erase(size_type pos = 0, size_type n = npos);

其中,pos表示要删除的子字符串的起始位置,n表示要删除的长度,省略n时则默认删除从pos开始到字符串末尾的所有字符。例如:

string str = "hello world";

str.erase(0, 5);

cout << str << endl; // 输出结果为" world"

insert()函数用于在字符串中插入子字符串,其基本语法如下:

basic_string& insert(size_type pos1, const basic_string& str);

其中,pos1表示要插入的位置,str表示要插入的子字符串。例如:

string str = "hello world";

str.insert(0, "hi ");

cout << str << endl; // 输出结果为"hi hello world"

以上就是C++中的字符串查找和替换方法,希望可以帮助大家更好地处理字符串操作。

  
  

评论区

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