C++ 標準庫字符串功能較弱 (無 split, trim, replace_all 等),封裝一套高性能、無依賴的字符串工具函數,支援 `std::string` 和 C 風格字符串。
| 函數 | 功能 | 關鍵實現點 |
|---|---|---|
split_string | 按分隔符分割字符串 | 用 strstr/find 定位,substr 提取,預留空間避免擴容 |
join_string | 連接字符串向量 | 預計算總長度 reserve,逐個 append |
replace_string | 全局替換子串 | 循環 find + substr 拼接新串,避免原地修改導致位置偏移 |
lstrip/rstrip/strip | 去除首/尾/兩端指定子串 | 從兩端向中間匹配,注意重疊情況 |
count_of_substr | 統計子串出現次數 | 循環 find 累計,支援重疊/不重疊兩種語義 |
lower_string/upper_string | 大小寫轉換 | ASCII 碼 ±32,或用 std::transform + ::tolower |
void split_string(const string& src, const string& sep, vector& out) { out.clear(); out.reserve(16); size_t pos = 0, next; while ((next = src.find(sep, pos)) != string::npos) { out.emplace_back(src, pos, next - pos); pos = next + sep.size(); } out.emplace_back(src, pos); // 最後一段 }
string replace_string(const string& src, const string& from, const string& to) {
if (from.empty()) return src;
string res; res.reserve(src.size() * 2);
size_t pos = 0, next;
while ((next = src.find(from, pos)) != string::npos) {
res.append(src, pos, next - pos);
res.append(to);
pos = next + from.size();
}
res.append(src, pos);
return res;
}
string strip(const string& src, const string& chars) {
size_t first = src.find_first_not_of(chars);
if (first == string::npos) return "";
size_t last = src.find_last_not_of(chars);
return src.substr(first, last - first + 1);
}
int main() {
vector parts;
split_string("a,b,c", ",", parts); // ["a","b","c"]
string joined = join_string("-", parts); // "a-b-c"
string replaced = replace_string("foo bar foo", "foo", "baz"); // "baz bar baz"
string stripped = strip(" hello ", " "); // "hello"
cout << count_of_substr("ababa", "aba") << endl; // 1 (不重疊) 或 2 (重疍)
return 0;
}
reserve 估算容量。string::find 系列而非手寫循環 (標準庫通常優化過)。string_view (C++17) 或 substr 引用語義。char* + 手寫 SIMD 優化。本庫實現了工程中高頻的字符串操作,代碼簡潔、無外部依賴、性能穩健。掌握「預留空間、流式構建、標準庫算法優先」三原則,可快速構建生產級字符串工具集。