c string類字串查詢

2021-10-24 05:22:55 字數 1346 閱讀 1653

1) find() 函式

find() 函式用於在 string 字串中查詢子字串出現的位置,它其中的兩種原型為:

size_t find (

const string& str, size_t pos =0)

const

;size_t find (

const

char

* s, size_t pos =0)

const

;

第乙個引數為待查詢的子字串,它可以是 string 字串,也可以是c風格的字串。第二個引數為開始查詢的位置(下標);如果不指明,則從第0個字元開始查詢。

請看下面的**:

#include

#include

using

namespace std;

intmain()

執行結果:

found at index : 6

find() 函式最終返回的是子字串第一次出現在字串中的起始下標。本例最終是在下標6處找到了 s2 字串。如果沒有查詢到子字串,那麼會返回乙個無窮大值 4294967295。

2) rfind() 函式

rfind() 和 find() 很類似,同樣是在字串中查詢子字串,不同的是 find() 函式從第二個引數開始往後查詢,而 rfind() 函式則最多查詢到第二個引數處,如果到了第二個引數所指定的下標還沒有找到子字串,則返回乙個無窮大值4294967295。

請看下面的例子:

#include

#include

using

namespace std;

intmain()

執行結果:

found at index : 6

3) find_first_of() 函式

find_first_of() 函式用於查詢子字串和字串共同具有的字元在字串中首次出現的位置。請看下面的**:

#include

#include

using

namespace std;

intmain()

執行結果:

found at index : 3

本例中 s1 和 s2 共同具有的字元是 』s』,該字元在 s1 中首次出現的下標是3,故查詢結果返回3。

C string類中的字串查詢

c string類中的字串查詢 類string提供了大量查詢功能和搜尋功能,其中比較常用的查詢和搜尋函式是find 函式 find first not of 函式 find first of 函式 find last not of 函式 find last of 函式 rfind 等。find 函式...

CString字串查詢和擷取

該函式從左側0索引開始,查詢第乙個出現的字元位置 cstring str abc int postion str.find a 如果查到,返回以0索引起始的位置 未查到,返回 1。給定一字串,然後查詢其中出現的第乙個字元位置 cstring str abc int position str.find...

CString字串查詢和擷取

1 find 該函式從左側0索引開始,查詢第乙個出現的字元位置,返回position。示例如下 cstring s abcdef assert s.find b 1 int f s.find de 結果 f 3 返回值 如果查到,返回以0索引起始的位置 未查到,返回 1 2 findoneof 給定...