Ciallo~ (∠?ω< )⌒★
string(1)
- 1. 構造函數
- 1.1 string();
- 1.2 string(const char* s);
- 1.3 string(const string& str);
- 1.4 string(size_t n, char c);
- 1.5 string(const string& str, size_t pos, size_t len = npos);
- 1.6 string(const char* s, size_t n);
- 2. 析構函數
- 3. 賦值運算符重載
- 4. 字符串的遍歷
- 4.1 下標+[]
- 4.2 迭代器
- 4.3 范圍for
- 5. string類對象的容量操作
- 6. string類對象的修改操作
- 7. string類非成員函數
1. 構造函數
string類有如下圖的構造函數:
其中比較重要的是1,2,4,6。
1.1 string();
無參的構造函數,定義了一個空字符串
string str1;
1.2 string(const char* s);
用常量串初始化
string str1("hello world!");
string str2 = "hello world!";
這兩種初始化方式的意義是不一樣的,str1是直接構造,str2是隱式類型轉換
1.3 string(const string& str);
這是string類的拷貝構造函數
string str1("hello world!");
string str2(str1);
1.4 string(size_t n, char c);
用n個字符c初始化
string str(10, '*'); //用10個*初始化str
1.5 string(const string& str, size_t pos, size_t len = npos);
字符串的截取,其中str是源字符串,pos是開始截取的位置,len是截取的長度
string str1 = "hello world";
string str2(str1, 2, 6);
輸出結果是:llo wo
1.6 string(const char* s, size_t n);
拷貝一個字符數組s的前n個元素
2. 析構函數
~string(),是string類已經寫好的,而且在程序結束時會自動調用,沒啥好說的。
3. 賦值運算符重載
str1 = "Test string: "; // c-string
str2 = 'x'; // single character
str3 = str1 + str2; // string
4. 字符串的遍歷
4.1 下標+[]
string str("hello world");
for (int i = 0; i < str.size(); i++)
{cout << str[i] << " ";
}
4.2 迭代器
string str("hello world");
string::iterator it = str.begin();
while (it != str.end())
{cout << *it << " ";++it;
}
cout << endl;
迭代器是通用的遍歷容器的方法,用原生指針或用封裝原生指針的自定義類實現。
4.3 范圍for
auto是C++11引入的關鍵字,用于自動推導變量類型。編譯器根據初始化表達式的類型推斷變量的實際類型,簡化代碼編寫并提升可讀性。
string str("hello world");
for (auto e : str)
{cout << e << " ";
}
5. string類對象的容量操作
函數名 | 功能 |
---|---|
size | 返回字符串的有效字符長度 |
length | 返回字符串的有效字符長度 |
capacity | 返回字符串總空間大小 |
empty | 判斷字符串是否為空,是則返回true,否則返回false |
clear | 清空有效字符 |
reserve | 為字符串預留空間 |
resize | 將有效字符個數設為n個,多出的空間用指定字符填充 |
注意當 reserve 的參數大于字符串底層總空間大小時,擴容,小于字符串底層總空間大小時不縮容。
當 resize 的參數大于字符串底層總空間大小時,調用reserve擴容。
6. string類對象的修改操作
函數名 | 功能 |
---|---|
push_back | 在字符串后尾插字符c |
append | 在字符串后追加一個字符串 |
operator+= | 在字符串后追加一個字符串 |
c_str | 將字符串以字符數組形式返回 |
find | 查找一個字符或字符串第一次出現的下標 |
substr | 從pos位置開始,向后截取n個字符,然后將其返回 |
7. string類非成員函數
函數 | 功能 |
---|---|
operator+ | 追加字符串 |
operator<< | 輸出運算符重載 |
operator>> | 輸入運算符重載 |
getline | 獲取一行字符串 |
rational operators | 字符串的大小比較 |