string的find 方法 c++
| string (1) | size_t find (const string& str, size_t pos = 0) const noexcept; |
|---|---|
| c-string (2) | size_t find (const char* s, size_t pos = 0) const; |
| buffer (3) | size_t find (const char* s, size_t pos, size_type n) const; |
| character (4) | size_t find (char c, size_t pos = 0) const noexcept; |
在c++11 中find的用法有以上四种,大体的形式为
str.find(s, pos)
其中,str为待查找的字符串,s为待查找的字符/字符串,pos为希望查找起始的位置,该参数默认为0。
下面举个例子
#include <iostream>
#include <string>
using namespace std;
int main(int argc, char const *argv[])
{
string str = "helloworld";
size_t idx = str.find('l');
cout << "l in str @ " << idx << endl;
size_t idx1 = str.find('l', 3);
cout << "l in str @ " << idx1 << endl;
return 0;
}
输出
l in str @ 2
l in str @ 3
两次的find输出都是字符’l’在str中的位置,第一个输出的是第一个字符’l’在str的位置;第二个输出为第二个字符在str的位置。
本文详细介绍了C++中字符串find方法的四种使用形式,包括查找字符串、C字符串、缓冲区和字符的方法,并通过示例代码展示了如何在指定位置开始查找特定字符及其返回的位置。
2291

被折叠的 条评论
为什么被折叠?



