認識 Aero / 字串

字串

Aero 的 str 是 NUL 結尾的 C 字串(malloc 管理)。這是和 C 互操作最順的表示。

基本操作

let s = "hello";
print(len(s));          // 5
print(s + " world");    // "hello world"(字面量拼接零成本)
print(s[0]);            // 104('h' 的數值)
len(s)字節長度
s1 + s2拼接(字面量零成本;變量參與需運行時分配)
== != < > <= >=字典序比較
s[i]第 i 字節的數值
int_to_str(n)整數 → 字串(需 str_free)
str_to_int(s)字串 → 整數(失敗返回 0)
substr(s, start, end)截取 [start, end)(需 str_free)
str_contains(hay, needle)是否包含
str_find(hay, needle)首次出現位置,找不到 -1
str_cmp(a, b)C 風格比較:負 / 0 / 正
str_free(s)釋放運行時分配的字串

運行時分配必須釋放

凡是運行時分配的字串(int_to_str、substr、變量拼接),用完要 str_free,否則泄漏。

let s = int_to_str(12345);
print(s);        // 12345
str_free(s);     // 釋放

文件讀寫

let text = read_file("data.txt");     // 讀整個文件,失敗返回空串
write_file("out.txt", text);          // 寫文件,返回字節數,失敗 -1
Aero 文档 · 基于 Aero 1.2.0 文档整理 · MIT
SereinTeam