C string的常用方法

2021-10-03 21:04:31 字數 1514 閱讀 3023

1).向string的後面加c-string

string s = 「hello 「; const char *c = 「out here 「; 

s = 「hello out here」;

2).向string的後面加c-string的一部分

string s=」hello 「;const char *c = 「out here 「; 

s = 「hello out」;

3).向string的後面加string

string s1 = 「hello 「; string s2 = 「wide 「; string s3 = 「world 「; 

s1 = 「hello wide 「; s1 = 「hello wide world 「;

4).向string的後面加string的一部分

string s1 = 「hello 「, s2 = 「wide world 「; 

s1 = 「hello world」;

string str1 = 「hello 「, str2 = 「wide world 「;

str1 = 「hello world」;

5).向string後面加多個字元

string s1 = 「hello 「; 

s1 = 「hello !!!!」;

改編自:

以下**錯誤,不能直接printf string。

int

main()

正確**應為:

int

main()

printf輸出字串是針對char*或char的。即printf只能輸出c語言中的內建資料,string不是c語言內建資料。

以上**中str1是string型別的物件,並非單單只有字串,其內還有許多用於操作的函式,於是&str1並非字串「test abc」的首位址,而是str1這個物件的首位址。

但string型別的資料可以用cout直接輸出:

int

main()

對於char或char*定義的字串可以直接printf。

如下**正確:

int

main()

執行結果為:

123456

test

s.substr(pos, n):

返回乙個string,包含s中從pos開始的n個字元的拷貝(pos的預設值是0,n的預設值是s.size() - pos,即不加引數會預設拷貝整個s)

若pos的值超過了string的大小,則substr函式會丟擲乙個out_of_range異常;若pos+n的值超過了string的大小,則substr會調整n的值,只拷貝到string的末尾。

CString常用方法

cstring left intncount const 從左邊1開始獲取前 ncount個字元 cstring mid intnfirst const 從左邊第 ncount 1個字元開始,獲取後面所有的字元 cstring mid intnfirst,intncount const 從左邊第 n...

CString的一些常用方法

cstringleft int ncount const 從左邊1開始獲取前ncount 個字元 cstringmid int nfirst const 從左邊第ncount 1 個字元開始,獲取後面所有的字元 cstringmid int nfirst,int ncount const 從左邊第n...

c string字串常用的方法

tochararray int startindex,int length 引數startindex 此例項內子字串的起始位置。length 此例項內子字串的長度。eg 將字串a複製為字元陣列d 引數value 要搜尋的字串。可判斷字元中是否出現在字串中,返回bool型 引數startindex 插...