c 資料型別 string

2021-08-23 13:10:56 字數 1016 閱讀 5968

string是c++標準類中的字串類,可以用它代替c風格的字串操作,來減少指標等底層因素引起的錯誤。

使用string類,

標頭檔案引用

#i nclude

#i nclude

#if _msc_ver > 1020

using namespace std;

#endif

其中,主要是要引用std名字空間。

定義

string str;

string str = "abcd";

string str("abcd");

string str2(str); //用另乙個string物件來構造

* 可以直接比較

if(str == str2)

* 可以用+, +=等操作

string str3 = str + str3;

str3+= str;

* c風格的字串可以自動轉化為string型別

const char *pc = ", ";

string str4 = str +pc +str2;

但是反過來就不可以。

char * c_str = str; //error

char * c_str = str.c_str(); //這樣也不對,因為為了防止直接對字串內容進行操作,返回const

const char * c_str = str.c_str(); //ok

* size()返回長度,不包含結束符

* empty() 可以直接判斷字串是否為空

*可訪問單個元素

cout<

* 迭代操作

for(string::iterator it = str.begin(); it != str.end(); it++)

c 資料型別string

c 中資料型別大部分和c語言都一樣,像整型,浮點,char,結構體,陣列等等,有區別的一點是c 中提供了字串型別string,更嚴謹一點,string是c 提供的乙個類。這一點是c語言中沒有的,c語言中是以字元陣列來儲存字串的。要使用string類,必須在程式中包含標頭檔案string。string...

資料型別 string

單引號建立字串 str0 php xust echo str0 echo 單引號中的單引號需要轉義 雙引號建立字串與單引號不同 可以解釋變數 str1 php echo str1 echo str3 php echo str3 echo 用heredoc 語法來建立字串 適用於大量字串的情況 優化的...

複雜的資料型別 string資料型別

include include 為了使用getline函式和在我們的程式中使用string型別,使用string型別時我們需要包含string字元標頭檔案 using namespace std define item 10 使用巨集定義變數 void calcsum void string int...