在c語言里,我們使用一個字符串時,是通過字符數組或者字符指針的方式來進行使用,在C++里,標准模板庫已經給我們提供了string類型(string是以類的方式提供給我們使用)。
定義和初始化string對象:
string str; // 默認初始化,此時str是一個空串
string str = "hello world"; // 用 "hello world"初始化str對象
string str("hello world"); // 用 "hello world"初始化str對象
string str1 = str2; // 用str2對象初始化str1
string str(5, 'a'); // 用5個'a'初始化str對象
string對象上常用的操作:
bool empty(); // 字符串是否為空
size() / length(); // 返回字符串長度
str[n]; // 返回str中位置n的字符,從0開始
str1 + str2; // 字符串連接,返回一個新字符串
str1 = str2; // 字串對象的賦值,區別於初始化
str1 == str2; // 判斷兩個字符串是否相等
str != str2; // 判斷兩個字符串是否不相等
str1 > str2;
str1 < str2;
str.c_str(); // 返回字符串的指針,C語言風格,為了與c語言風格字符串兼容
cin >>str; // 輸入字符串,遇到空格結束
cout <<str;
for (auto &ch : str) // 基於范圍的循環
push_back(char ch); // 字符串末尾添加字符ch
insert(pos, ch); // 位置pos之前插入字符ch
clear(); // 清空字符串
// 查找字符串s在str中首次出現的位置,找不到返回-1
size_t find (const char* s, size_t pos = 0) const;
// 查找字符c在str中首次出現的位置,找不到返回-1
size_t find (char c, size_t pos = 0) const;
注: 以上只是列出自己平時常用的字符串操作,並不是全部。