admin 管理员组

文章数量: 1087139


2024年4月17日发(作者:怎么把网页变成代码)

c++的string的find用法

C++的字符串类(string)提供了一个名为`find()`的函数用于在

字符串中查找子字符串。它的准确用法如下:

```cpp

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

```

这个函数返回子字符串`str`在字符串中第一次出现的位置,如果

找不到则返回`string::npos`。参数`pos`表示在字符串中查找的起始

位置,默认为0,即从字符串的开头开始搜索。

具体用法如下:

```cpp

#include

#include

int main() {

std::string str = "Hello, World!";

//查找子字符串", "

size_t found = (", ");

if (found != std::string::npos) {

std::cout << "找到子字符串", ",位置为:" << found <<

std::endl;

} else {

std::cout << "未找到子字符串", "" << std::endl;

}

return 0;

}

```

输出结果为:

```

找到子字符串", ",位置为:5

```

除此以外,使用`find()`函数还可以进行更多的操作,如查找所

有匹配项、查找最后一次出现的位置等。下面是一些常用的拓展用法:

1.查找所有匹配项:可以使用一个循环来重复调用`find()`函数,

每次从上一次找到的位置的后面开始查找,直到找不到为止。

```cpp

std::string str = "abcbcabd";

std::string subStr = "abc";

size_t found = (subStr);

while (found != std::string::npos) {

std::cout << subStr << "出现在位置:" << found <<

std::endl;

found = (subStr, found + 1);

}

```

输出结果为:

```

abc出现在位置:0

abc出现在位置:4

```

2.查找最后一次出现的位置:可以先使用`rfind()`函数找到最后

一次出现的位置,然后再从该位置开始使用`find()`函数查找其他匹

配项。

```cpp

std::string str = "abcbcabd";

std::string subStr = "abc";

size_t found = (subStr);

while (found != std::string::npos) {

std::cout << subStr << "最后一次出现的位置:" << found <<

std::endl;

found = (subStr, found - 1);

}

```

输出结果为:

```

abc最后一次出现的位置:4

abc最后一次出现的位置:0

```

以上内容为c++的string的find用法。


本文标签: 字符串 位置 查找 出现