string中的find函数怎么用
时间: 2024-04-23 12:29:14 浏览: 11
在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函数的使用方法
在 C++ 中,`string` 类型的 `find` 函数可以用来查找一个子串在字符串中出现的位置。它的使用方法如下:
```c++
size_t find(const string& str, size_t pos = 0) const noexcept;
```
其中,`str` 是要查找的子串,`pos` 是查找的起始位置(默认为 0),函数会返回子串在字符串中第一次出现的位置,如果找不到则返回 `string::npos`。
示例代码如下:
```c++
#include <iostream>
#include <string>
using namespace std;
int main() {
string str = "hello world";
string sub = "world";
size_t pos = str.find(sub);
if (pos != string::npos) {
cout << "子串在字符串中的位置:" << pos << endl;
} else {
cout << "子串未找到" << endl;
}
return 0;
}
```
输出结果为:
```
子串在字符串中的位置:6
```
string中的find函数
string中的find函数用于查找一个子字符串在原字符串中第一次出现的位置。它的语法如下:
```
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;
```
其中,第一个参数可以是一个字符串或者是一个字符,第二个参数指定了查找的起始位置,默认是从字符串的开头开始查找。如果找到了指定的子字符串或字符,返回它在原字符串中的位置,否则返回`string::npos`。注意,`string::npos`是一个常量,它的值为-1,表示没有找到指定的子字符串或字符。