C++ std::string 是處理可變長度字符串的標準工具。它自動管理底層內存,提供豐富的操作介面,滿足絕大多數字符串處理需求。本文系統梳理 string 的構造、輸入輸出、常用操作及核心注意事項。
string 提供多種構造函數,支援多樣化的初始化場景:
// 預設構造,空字符串
string s1;
// 拷貝構造
string s2(s1);
// 從 C 風格字符串字面值構造
string s3("value");
// 由 n 個字符 c 構造
string s4(4, 'c'); // "cccc"
C++11 擴充了構造選項,包含子串、緩衝區、迭代器範圍、初始化列表及移動語意:
string() — 預設構造string(const string& str) — 拷貝構造string(const string& str, size_t pos, size_t len = npos) — 子串構造string(const char* s) — 從 C 字符串構造string(const char* s, size_t n) — 從緩衝區前 n 字符構造string(size_t n, char c) — 填充構造template <class InputIterator> string(InputIterator first, InputIterator last) — 迭代器範圍構造string(initializer_list<char> il) — 初始化列表構造string(string&& str) noexcept — 移動構造標準輸入輸出流直接支援 string:
string s;
cin >> s; // 讀取:跳過前導空白,直到遇到下一個空白
cout << s << endl; // 輸出
注意:operator>> 以空白(空格、換行、製表符)為分隔符。若需讀取整行(含空格),請使用 getline(cin, s)。
| 操作 | 說明 |
|---|---|
s.empty() | 若為空串返回 true |
s.size() | 返回字符數量,類型為 string::size_type(無符號整數) |
s[n] | 返回位置 n 的字符引用(0 起索引,無邊界檢查) |
s1 + s2 | 連接生成新字符串 |
s1 = s2 | 賦值拷貝 |
s1 == s2 | 內容比較,支援 !=, <, <=, >, >= |
size_type 的重要說明string::size_type 是標準庫定義的配套類型,保證能容納任意 string 長度,通常等同於 size_t。使用時需加作用域:
string::size_type len = s.size(); // 最安全的做法
s[n] 不做邊界檢查;s.at(n) 會拋出 out_of_range 異常,更安全。
#include <string>
#include <iostream>
using namespace std;
int main() {
// 初始化示例
string s1; // 空串
string s2(s1); // 拷貝
string s3("value"); // 字面值
string s4(4, 'c'); // "cccc"
// 輸入輸出
string s;
cin >> s;
cout << s << endl;
// size() 與 empty()
string S("this");
cout << "the size of " << S << " is " << S.size() << endl;
return 0;
}