C string 字串的下標和子串函式

2021-08-26 17:15:30 字數 1880 閱讀 4834

可以用assign()函式來設定字串的元素,也可以用下標運算子和成員函式at()來檢索字串中的某個字元

或修改字串中的某個字元。

assign()函式的主要語法如下所示:

//將str的內容賦值給string物件

string& assign ( const string& str );

//將str的內容從pos開始取n個賦值給string物件

string& assign ( const string& str, size_t pos, size_t n );

//將s所指向的字元陣列的前n給賦值給string物件

string& assign ( const char* s, size_t n );

//將s所指向的字元陣列賦值給string物件

string& assign ( const char* s );

//將n個c字元賦值給string物件

string& assign ( size_t n, char c );

//假如inputiterator是int型別,該函式與string& assign ( const char* s, size_t n )功能一樣

//如果是其他型別,則將該型別第first個開始到last結束的值賦給string物件

template

string& assign ( inputiterator first, inputiterator last );

例項如下:

#include #include using namespace std;

int main(int argc, char *argv)

執行結果如下:

the quick brown fox jumps over a lazy dog.

brown fox

pangram

c-string

**********

----------

fox jumps over

at()函式的語法如下所示:

//獲取string物件第pos個的字元,並將其返回

const char& at ( size_t pos ) const;

char& at ( size_t pos );

例項如下:

// string::at

#include #include using namespace std;

int main ()

return 0;

}

執行結果如下:

test string

substr()函式可以從乙個字串中提取並返回子串,函式的第乙個引數是子串在原始字串中的起始位置

(計數從0開始),第二個引數是子串的字元個數。其語法如下所示

string substr ( size_t pos = 0, size_t n = npos ) const;

例項如下:

#include #include using namespace std;

int main(int argc, char *argv)

執行結果如下:

generalities live in details.

其他函式:

begin() 該函式的功能是返回字串第一元素的指示器

end() 該函式的功能是返回字串最後乙個元素的指示器

capacity () 該函式的功能是返回字串的分配空間,它至少大於等於size()函式的返回值

compare() 該函式的功能是比較兩個字串

字串擷取和下標獲取

1 match 方法可在字串內檢索指定的值,或找到乙個或多個正規表示式的匹配。2 indexof 方法可返回某個指定的字串值在字串中首次出現的位置。3 lastindexof 方法可返回乙個指定的字串值最後出現的位置,在乙個字串中的指定位置從後向前搜尋。4 substring 方法用於提取字串中介於...

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 給定...