C++ string的查找函数和npos特殊值

时间:2023-03-09 16:49:53
C++ string的查找函数和npos特殊值

STL中的string有6个查找函数:

1.find()

2.rfind()

从最后一个字符开始往前找。

3.find_first_of()

4.find_not_first_of()

5.find_last_of()

6.find_not_last_of()

所有这些查找函数返回值都是size_type类型(找到了)或者是一个名为 string::npos的特殊值(没找到)。

string::npos常用来表示没找到的结果或者string类型的末尾。

#include <iostream>
#include <bitset>
#include <string> int main()
{
// string search functions return npos if nothing is found
std::string s = "test";
if(s.find('a') == std::string::npos)
std::cout << "no 'a' in 'test'\n"; // functions that take string subsets as arguments
// use npos as the "all the way to the end" indicator
std::string s2(s, , std::string::npos);
std::cout << s2 << '\n'; std::bitset<> b("aaabb", std::string::npos, 'a', 'b');
std::cout << b << '\n';
}
//输出结果
/*
no 'a' in 'test'
st
00011
*/