std string 的常用使用

2021-06-16 05:52:13 字數 2324 閱讀 3487

用 string來代替char * 陣列,使用sort排序演算法

來排序,用unique 函式

, , <<, >>等,正式這些操作符,對字串操作非常方便

#include

#include

using

namespace std;

int main()

5、find函式

由於查詢是使用最為頻繁的功能之一,string 提供了非常豐富的查詢函式。其列表如下:

函式名描述

find

查詢rfind

反向查詢

find_first_of

查詢包含子串中的任何字元,返回第乙個位置

find_first_not_of

查詢不包含子串中的任何字元,返回第乙個位置

find_last_of

查詢包含子串中的任何字元,返回最後乙個位置

find_last_not_of

查詢不包含子串中的任何字元,返回最後乙個位置

以上函式都是被過載了4次,以下是以find_first_of 函式為例說明他們的引數,其他函式和其引數一樣,也就是說總共有24個函式:

size_type find_first_of(const basic_string& s, size_type pos = 0)

size_type find_first_of(const chart* s, size_type pos, size_type n)

size_type find_first_of(const chart* s, size_type pos = 0)

size_type find_first_of(chart c, size_type pos = 0)

所有的查詢函式都返回乙個size_type型別,這個返回值一般都是所找到字串的位置,如果沒有找到,則返回string::npos。

其實string::npos表示的是-1。即沒找到就返回-1。例子如下:

#include

#include

using

namespace std;

int main()

int last = strinfo.find_last_of(strset);

if(last == string::npos)

cout << strinfo.substr(first, last - first + 1)}6、insert函式, replace函式和erase函式

string只是提供了按照位置和區間的replace函式,而不能用乙個string字串來替換指定string中的另乙個字串。

例子:#include

#include

using

string s(cstr)            以c-string cstr作為s的初值

string s(num,c)           生成乙個字串,包含num個c字元

string s(beg,end)         以區間[beg,end]內的字元作為s初值

s.~string() 銷毀所有字元,釋放記憶體

注意:std::string s('x');//error

std::string s(1,'x'); //ok,create a string that has one charactor 'x'

9、substr(string.substr的方法)

(1)引數

start:number -- 乙個整數,指示 my_str 中用於建立子字串的第乙個字元的位置。如果 start 為乙個負數,則起始位置從字串的結尾開始確定,其中 -1 表示最後乙個字元。

length:number -- 要建立的子字串中的字元數。如果沒有指定 length,則子字串包括從字串開頭到字串結尾的所有字元。

(2)返回

string -- 指定字串的子字串。

(3)示例

下面的示例建立乙個新字串 my_str,並使用 substr() 返回該字串中的第二個單詞;首先,使用正的 start 引數,然後使用負的 start 引數:

var my_str:string = new string("hello world");

var mysubstring:string = new string();

mysubstring = my_str.substr(6,5);

trace(mysubstring); // 輸出:world

mysubstring = my_str.substr(-5,5);

trace(mysubstring); // 輸出:world

std string 的常用使用

轉 std string 的常用使用 std string 的常用使用 用 string來代替char 陣列,使用 sort排序演算法來排序,用 unique 函式來去重 1 define string s1 hello string s2 world string s3 s1 s2 n s1 sh...

std string 的常用使用

std string 的常用使用 用 string來代替char 陣列,使用sort排序演算法 來排序,用unique 函式 include include using namespace std int main 5 find函式 由於查詢是使用最為頻繁的功能之一,string 提供了非常豐富的查...

std string 的常用使用

相關網帖 用 string來代替char 陣列,使用 sort排序演算法來排序,用 unique 函式來去重 1 define string s1 hello string s2 world string s3 s1 s2 n s1 shanshan n 3 compare if s1 s2 els...