#include string>
#include iostream>
using namespace std;
void main()
{
復制代碼 代碼如下:
////find函數返回類型 size_type
string s("1a2b3c4d5e6f7g8h9i1a2b3c4d5e6f7g8ha9i");
string flag;
string::size_type position;
//find 函數 返回jk 在s 中的下標位置
position = s.find("jk");
nbsp;if (position != s.npos) //如果沒找到,返回一個特別的標志c++中用npos表示,我這里npos取值是4294967295,
nbsp;{
nbsp;nbsp;cout "position is : " position endl;
nbsp;}
nbsp;else
nbsp;{
nbsp;nbsp;cout "Not found the flag" + flag;
nbsp;}nbsp;
復制代碼 代碼如下:
//find 函數 返回flag 中任意字符 在s 中第一次出現的下標位置
flag = "c";
position = s.find_first_of(flag);
cout "s.find_first_of(flag) is : " position endl;
復制代碼 代碼如下:
//從字符串s 下標5開始,查找字符串b ,返回b 在s 中的下標
position=s.find("b",5);
cout"s.find(b,5) is : "positionendl;
復制代碼 代碼如下:
//查找s 中flag 出現的所有位置。
flag="a";
position=0;
int i=1;
while((position=s.find_first_of(flag,position))!=string::npos)
{
//position=s.find_first_of(flag,position);
cout"position "i" : "positionendl;
position++;
i++;
}
復制代碼 代碼如下:
//查找flag 中與s 第一個不匹配的位置
flag="acb12389efgxyz789";
position=flag.find_first_not_of (s);
cout"flag.find_first_not_of (s) :"positionendl;
復制代碼 代碼如下:
//反向查找,flag 在s 中最后出現的位置
flag="3";
position=s.rfind (flag);
cout"s.rfind (flag) :"positionendl;
}
說明:
1.如果string sub = ”abc“;
string s = ”cdeabcigld“;
s.find(sub) , s.rfind(sub) 這兩個函數,如果完全匹配,才返回匹配的索引,即:當s中含有abc三個連續的字母時,才返回當前索引。
s.find_first_of(sub), s.find_first_not_of(sub), s.find_last_of(sub), s.find_last_not_of(sub) 這四個函數,查找s中含有sub中任意字母的索引。
2.如果沒有查詢到,則返回string::npos,這是一個很大的數,其值不需要知道。
您可能感興趣的文章:- Nodejs libuv運行原理詳解
- 虛函數表-C++多態的實現原理解析
- c++中new的三種用法詳細解析
- 淺析C++中結構體的定義、初始化和引用
- c++ vector(向量)使用方法詳解(順序訪問vector的多種方式)
- C++二叉樹結構的建立與基本操作
- C++ 迷宮游戲實現代碼
- C++生成dll和調用dll的方法實例
- C++實現簡單的圖書管理系統
- 淺析C/C++中sort函數的用法
- C++類靜態成員與類靜態成員函數詳解
- 詳解c++ libuv工作隊列