string find()
时间: 2023-08-14 08:08:33 浏览: 33
`string find()` 是 C++ 中的一个字符串成员函数,它用于在一个字符串中查找另一个子字符串的位置。它返回一个整数值,表示找到的子字符串在原字符串中的起始位置,如果未找到则返回 `string::npos`。例如,下面的代码可以在字符串 `str` 中查找子字符串 `"hello"`:
```
string str = "world, hello!";
size_t pos = str.find("hello");
if (pos != string::npos) {
cout << "The substring was found at position " << pos << endl;
} else {
cout << "The substring was not found." << endl;
}
```
相关问题
string find
`string find` 是 C++ 中的一个成员函数,用于在一个字符串中查找指定子字符串的位置。它的语法如下:
```cpp
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;
```
其中,第一个参数可以是一个字符串对象、一个 C-style 字符串(即以 null 结尾的字符数组)或一个单个字符。第二个参数是可选的,表示从哪个位置开始查找,如果不指定,则默认从字符串的开头开始查找。
如果查找成功,则返回子字符串第一次出现的位置,如果查找失败,则返回 `string::npos`,它是一个静态常量,表示没有找到指定子字符串。
例如,下面的代码演示了如何使用 `find` 函数在字符串中查找子字符串:
```cpp
#include <iostream>
#include <string>
int main() {
std::string str = "hello, world!";
std::string sub = "world";
size_t pos = str.find(sub);
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 7
```
stringfind
在C++中,string类提供了几个用于查找子字符串或字符的方法。其中包括find(),rfind(),find_first_of(),find_last_of(),find_first_not_of()和find_last_not_of()等方法。这些方法可以在字符串中搜索指定的子字符串或字符,并返回第一个匹配的位置。如果找不到匹配的位置,这些方法会返回string::npos。<span class="em">1</span><span class="em">2</span><span class="em">3</span>
#### 引用[.reference_title]
- *1* *2* [string类的find()函数总结](https://blog.csdn.net/shujh_sysu/article/details/52026108)[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^v92^chatsearchT0_1"}}] [.reference_item style="max-width: 50%"]
- *3* [string的find( )函数✅](https://blog.csdn.net/weixin_45884316/article/details/108235945)[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^v92^chatsearchT0_1"}}] [.reference_item style="max-width: 50%"]
[ .reference_list ]