通常来说,find函数用于寻找某个序列的在string中第一次出现的位置。
find函数有以下四种重载版本:
|
1
2
3
4
|
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_type n)
const
;
size_t
find (
char
c,
size_t
pos = 0)
const
noexcept;
|
参数说明:
str/s/c:要寻找的序列,可以是字符串(版本1),也可以是字符串字面值或者说C风格字符串(版本2、3,在版本3中,所寻找的序列是从s[0]开始的前n个字符),也可以是字符(版本4)。
pos:从string的pos位置开始寻找(注意第一个位置是0)。
函数返回序列第一次出现的位置,如果没有找到则返回string::npos。
样例:(摘自cplusplus.com)
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
|
#include <iostream> // std::cout
#include <string> // std::string
int
main ()
{
std::string str (
"There are two needles in this haystack with needles."
);
std::string str2 (
"needle"
);
// different member versions of find in the same order as above:
std::
size_t
found = str.find(str2);
if
(found!=std::string::npos)
std::cout <<
"first 'needle' found at: "
<< found <<
'\n'
;
found=str.find(
"needles are small"
,found+1,6);
if
(found!=std::string::npos)
std::cout <<
"second 'needle' found at: "
<< found <<
'\n'
;
found=str.find(
"haystack"
);
if
(found!=std::string::npos)
std::cout <<
"'haystack' also found at: "
<< found <<
'\n'
;
found=str.find(
'.'
);
if
(found!=std::string::npos)
std::cout <<
"Period found at: "
<< found <<
'\n'
;
// let's replace the first needle:
str.replace(str.find(str2),str2.length(),
"preposition"
);
std::cout << str <<
'\n'
;
return
0;
}
|
标准输出结果:
first 'needle' found at: 14
second 'needle' found at: 44
'haystack' also found at: 30
Period found at: 51
There are two prepositions in this haystack with needles.
详解find函数
本文介绍了C++标准库中string类的find函数的四种不同重载版本及其使用方法,并通过实例展示了如何利用这些函数来查找字符串中特定子串或字符的位置。
974

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



