2024年3月26日发(作者:)

c++字符串查找函数

在C++编程语言中,字符串的查找是一项非常重要的技能。在实

际开发过程中,我们经常需要找到字符串中的某个子串或者判断一个

字符串是否包含另一个字符串。为此,C++提供了多种字符串查找函数,

本文将会介绍其中的几种。

1. strstr函数

strstr函数是C++中最常用的字符串查找函数之一,其原型为:

```c++

char* strstr(char* str1, const char* str2);

```

该函数用于查找字符串 str1 中是否包含某个子串 str2,并返

回该子串在 str1 中的地址。如果返回值为 NULL,则表示 str1 中不

包含该子串。

示例代码:

```c++

#include

#include

using namespace std;

int main() {

char str1[50] = "hello world";

char str2[10] = "world";

char* p = strstr(str1, str2);

if (p) {

cout << "子串在字符串中的位置:" << p - str1 << endl;

}

else {

cout << "字符串中不包含该子串!" << endl;

}

return 0;

}

```

2. strchr函数

strchr函数用于查找字符串 str 中第一个出现的指定字符 ch,

并返回该字符在字符串 str 中的地址。如果字符串 str 中不包含该

字符,则返回 NULL。

函数原型为:

```c++

char* strchr(char* str, int ch);

```

示例代码:

```c++

#include

#include

using namespace std;

int main() {

char str[50] = "hello world";

char ch = 'o';

char* p = strchr(str, ch);

if (p) {

cout << "字符在字符串中的位置:" << p - str << endl;

}

else {

cout << "字符串中不包含该字符!" << endl;

}

return 0;

}

```

3. string类中的find函数

C++中的string类也提供了查找子串的函数 find,其原型为:

```c++

size_t find(const string& str, size_t pos = 0) const;

```

该函数用于在字符串中查找另一个子串 str,并返回该子串在原

字符串中的位置。如果字符串中不包含该子串,则返回 string::npos。

示例代码:

```c++

#include

#include

using namespace std;

int main() {

string str1 = "hello world";

string str2 = "world";

size_t pos = (str2);

if (pos != string::npos) {

cout << "子串在字符串中的位置:" << pos << endl;

}

else {

cout << "字符串中不包含该子串!" << endl;

}

return 0;

}

```

以上是三种常用的字符串查找函数,当然还有其他的查找函数,

比如 std::regex_match、std::find_first_of等等,大家可以根据自

己的需要选择使用。在实际编程中,要根据需求选择合适的函数,以

便高效地完成字符串查找的任务。