C++中的std::string類包含了多種構造函數,可以方便地初始化字符串。以下是一些常見的std::string構造函數:
std::string();
創建一個空字符串,即長度為0的字符串。 2. 從C風格字符串構造
std::string(const char* s);
使用以’\0’結尾的C風格字符串s來初始化std::string對象。
3. 指定長度的C風格字符串構造
std::string(const char* s, size_t n);
使用C風格字符串s的前n個字符來初始化std::string對象。這里不需要以’\0’結尾。
4. 復制構造函數
std::string(const std::string& str);
通過復制另一個std::string對象str來初始化新的std::string對象。
5. 子字符串構造
std::string(const std::string& str, size_t pos, size_t len = npos);
從str中提取一個子字符串,從位置pos開始,長度為len。如果未指定len或者len大于str的剩余長度,則子字符串將一直擴展到str的末尾。
6. 填充構造函數
std::string(size_t n, char c);
創建一個長度為n的字符串,其中每個字符都被初始化為c。
7. 通過迭代器構造
template<class InputIt>
std::string(InputIt first, InputIt last);
使用由迭代器first和last指定的字符范圍來初始化字符串。注意,這是一個模板構造函數,可以接受任何類型的迭代器。
8. 移動構造函數
std::string(std::string&& str) noexcept;
通過“移動”而非復制的方式,從另一個std::string對象str來初始化新的std::string對象。這通常會使得原始字符串變為空,并且操作是高效的。
9. 初始化列表構造函數
std::string(std::initializer_list<char> il);
使用一個初始化列表il來初始化字符串。例如:std::string s = {'a', 'b', 'c'};。
以上就是C++中std::string類的一些常見構造函數。