C string類介面及模擬實現

2021-10-10 22:03:08 字數 2413 閱讀 4796

c語言中,字串是以 『\0』 結尾的一些字元的集合,為了操作方便,c標準庫中提供了一些str系列的庫函式,但是這些庫函式與字串是分離開的,而且底層空間需要使用者自己管理,稍不留神可能還會越界訪問。

c++封裝了這些介面和操作,建立出string類:

string 是表示字串的類

該類的介面與常規容器的介面基本相同,還新增了一些專門用來操作 string 的常規操作。

不能操作多位元組或者變長字元的序列

為什麼要將vector和string分開實現?

字串預設最後放 『\0』,而vector儲存資料時不需要

string 裡封裝了c語言中字串的操作介面,這些介面需要 『\0』 作為尾部

#include

#include

using

namespace std;

intmain()

} cout << endl;

str.

reserve(50

);// 底層容量和有效元素都不變

cout << str.

capacity()

<< endl;

str.

reserve(15

);// 底層容量和有效元素都不變

cout << str.

capacity()

<< endl;

// 有效元素

str1.

resize(50

,'a');

// 有效元素變成50個,容量63

str1.

resize(4

);// 有效元素變成4個,容量不變

// 迭代器和遍歷方式

for(size_t i =

0; i < str1.

size()

; i++

) cout << str1[i]

; cout << endl;

string::iterator it = str1.

begin()

;while

(it != str1.

end())

cout << endl;

for(

auto ch : str1)

cout << ch;

cout << endl;

// 修改操作

str1.

push_back

(' ');

str1.

("hello");

str1 +

='a'

; str1 +

="it"

;// 查詢操作

size_t pos1 = str1.

find

("it");

size_t pos2 = str1.

rfind

("lo");

return0;

}

小結:

#include

namespace traditional

string

(const string& s)

:_str

(new

char

[s.size()

+1])

~string()

} string&

operator=(

const string& s)

return

*this;}

intsize()

const

char

*c_str()

const

private

:char

* _str;};

}

注意:string 類作為函式返回值時,臨時拷貝構造的物件的 _str 不為 nullptr,而是隨機值。因此必須在拷貝構造初始化時賦空

namespace modern

string

(const string& s)

:_str

(nullptr)~

string()

} string&

operator

=(string s)

intsize()

const

char

*c_str()

const

private

:char

* _str;};

}

寫時拷貝:多個物件共用同乙份記憶體資源,當乙個物件的內容即將發生變化時,給這個物件重新分配記憶體並拷貝原空間內容。如果不進行修改,則由引用計數進行計算什麼時候進行釋放資源。

C string類 模擬實現

define crt secure no warnings include include using namespace std namespace zyf iterator end mystring const char str size strlen str mystring s1 s2 my...

C string類的模擬實現

include include using namespace std class string iterator end const iterator begin const const iterator end const string const char str 字串有 0 也可以寫成 0 ...

C string的模擬實現

define crt secure no warnings include include using namespace std class string iterator end const iterator begin const const iterator end const 預設無參構造...