string的find函数
时间: 2023-10-11 10:13:10 浏览: 63
在C++中,可以使用string类的find函数来查找字符串中是否包含某个子字符串。该函数的使用方法为:
string s = "hello world";
string::size_type index = s.find("world");
其中,s是要查找的字符串,"world"是要查找的子字符串。函数返回的是子字符串在原字符串中第一次出现的位置,如果没有找到则返回string::npos。可以用如下代码来判断查找结果:
if (index != string::npos) {
cout << "找到了,位置在:" << index << endl;
} else {
cout << "没有找到" << endl;
}
相关问题
string find函数
`std::string::find` 是一个字符串查找函数,可用于在一个字符串中查找子串的位置。它的函数原型为:
```c++
size_t find(const string& str, size_t pos = 0) const noexcept;
size_t find(const char* s, size_t pos = 0) const;
size_t find(const char* s, size_t pos, size_t n) const;
size_t find(char c, size_t pos = 0) const noexcept;
```
其中,参数 `str` 表示要查找的子串,参数 `pos` 表示从哪个位置开始查找,返回值是子串第一次出现的位置。如果未找到子串,则返回 `std::string::npos`。
例如:
```c++
#include <iostream>
#include <string>
int main() {
std::string str = "hello world";
std::string sub_str = "world";
size_t pos = str.find(sub_str);
if (pos != std::string::npos) {
std::cout << "Found at position " << pos << std::endl;
} else {
std::cout << "Not found" << std::endl;
}
return 0;
}
```
输出:
```
Found at position 6
```
string find函数参数
find函数的参数是两个字符串:被搜索的字符串和要查找的子字符串。具体格式如下:
```
int find(const string& str, const string& sub_str);
```
其中,`str`是被搜索的字符串,`sub_str`是要查找的子字符串。该函数会返回子字符串在被搜索的字符串中第一次出现的位置。如果找不到子字符串,会返回一个特殊值`string::npos`。