c++中string类型中find_first_not_of是什么功能
时间: 2023-06-01 20:07:41 浏览: 74
find_first_not_of 是 C++ 中 string 类型的一个成员函数,用来查找字符串中第一个不匹配指定字符集合的字符。它的语法为:int find_first_not_of(const char* s, int pos = 0),其中 s 是一个字符集合,pos 为查找起始位置(默认从字符串开头查找)。如果找到则返回该字符的位置,否则返回 -1。举例来说,字符串 "hello world",若输入字符集为 "hel",则该函数返回 3,因为第一个不属于字符集 "hel" 的字符是 'o',其位置为 3。
相关问题
c++中find_first_of()
在 C++ 中,`find_first_of()` 是一个字符串函数,用于查找一个字符串中的任何字符是否出现在另一个字符串中。
函数原型如下:
```c++
size_t find_first_of (const string& str, size_t pos = 0) const noexcept;
size_t find_first_of (const char* s, size_t pos, size_t n) const;
size_t find_first_of (const char* s, size_t pos = 0) const;
size_t find_first_of (char c, size_t pos = 0) const noexcept;
```
其中,第一个参数 `str` 是要查找的字符串;第二个参数 `pos` 是从哪个位置开始查找,默认值为 0。
如果找到了匹配的字符,则函数返回该字符在字符串中的位置,否则返回 `string::npos`。
示例代码:
```c++
#include <iostream>
#include <string>
int main() {
std::string str1 = "Hello World";
std::string str2 = "abcde";
size_t found = str1.find_first_of(str2);
if (found != std::string::npos) {
std::cout << "Found character " << str1[found] << " at position " << found << '\n';
} else {
std::cout << "No match found.\n";
}
return 0;
}
```
输出结果:
```
Found character l at position 2
```
find_first_not_of
find_first_not_of()函数是用来在一个字符串中查找第一个不属于指定字符集合的字符的位置。它与find_first_of()函数的功能相反。\[1\]该函数会从字符串的前面往后面搜索,直到找到第一个不属于指定字符集合的字符,并返回其位置。如果找不到符合条件的字符,则返回string::npos。\[3\]下面是一个使用find_first_not_of()函数的示例代码:
```cpp
#include <iostream>
#include <string>
using namespace std;
int main() {
string s = "hello world";
string chars = "abcdefghijklmnopqrstuvwxyz";
int pos = s.find_first_not_of(chars); // 在s中查找第一个不属于字母表的字符
cout << pos << endl; // 输出结果为:5
return 0;
}
```
在上述代码中,我们定义了一个字符串s和一个字符集合chars,然后使用find_first_not_of()函数在字符串s中查找第一个不属于字母表的字符的位置。由于字符'l'是字母表中的字符,所以函数返回的位置是5。
#### 引用[.reference_title]
- *1* *2* *3* [C++中的find函数用法](https://blog.csdn.net/qq_51271013/article/details/116170964)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^insert_down1,239^v3^insert_chatgpt"}} ] [.reference_item]
[ .reference_list ]