# 字符串 字符串操作是裸标准库动词,在每个运行时中都可用。索引基于码点: `len` 统计字符数,`$s(a..b)` 切片、`nth`、`char-at` 和 `index-of` 都以完整字符为单位操作——切片永远不会落在字符中间。字符串内部是 UTF-8 字节数组且二进制安全;`bytes/*` 动词为二进制数据提供原始访问。 显示宽度(东亚宽字形占 2 个终端单元格)是另一个问题:在终端网格中 定位文本时,请使用宽度动词,而不是 `len`。完整说明见 字符串表示。 ## 函数 核心字符串操作: | 函数 | 用途 | |---|---| | `str $xs...` | 将多个值拼接为字符串 | | `format fmt args...` | Printf 风格格式化(`%d %x %f %s ...`,支持标志/宽度/精度) | | `upper s`, `lower s` | 大小写转换 | | `trim s` | 去除首尾空白 | | `split s sep` | 拆分为列表(`sep` 为空时按字符拆分) | | `join xs sep` | 将列表连接为字符串 | | `replace s old new` | 替换所有出现 | | `replace-first s old new` | 仅替换第一次出现 | | `starts-with? s prefix`, `ends-with? s suffix` | 前缀/后缀谓词 | | `repeat s n` | 将字符串重复 `n` 次 | | `lines s` | 按换行符拆分 | | `words s` | 按空白拆分 | | `contains s substr` | 子串检查 | | `reverse s` | 按码点反转(多字节字符保持完整) | | `char-at s i` | 指定码点索引处的字符(越界返回 nil) | | `index-of s sub` | 查找子串的码点索引,找不到返回 -1 | | `chars/count s`, `chars/slice s a b` | 显式字符计数/区间 | 布局(显示宽度)——在终端单元格 UI 中定位文本时,请使用这些函数,而非 `len`: | 函数 | 用途 | |---|---| | `width s` | 以单元格计的显示宽度(东亚宽字符 = 2) | | `cells s` | 每个字符的 `@{char-index char-string width}` 三元组 | | `truncate-width s w ?tail` | 适配 `w` 个单元格的最长前缀(可选 "…" 尾部) | | `pad-width-left/right s w ?fill` | 填充到指定显示宽度 | | `wrap-width s w` | 按显示宽度换行,返回行列表 | | `pad-left s n ch`, `pad-right s n ch` | 填充到指定字符数 | 字节(二进制数据)——用于 `fs/read` 读到的内容、加密和协议偏移量, 这些场景中分块边界绝不能错位: | 函数 | 用途 | |---|---| | `bytes/len s` | 字节长度 | | `bytes/slice s a b` | 原始字节区间 | | `byte-at s i` | 字节值(0-255) | 码点动词是文本层:`char-at` 和 `index-of` 绝不会返回原始字节片段, 空分隔符的 `split` 产出完整字符。字节动词是数据层:用于编码数据块、 协议偏移量,以及任何恰好包含 UTF-8 片段的内容。`width` 度量终端 单元格;无效的 UTF-8 字节每个计 1。字符分类(`chars/alpha?`、 `chars/digit?` 等)参见 字符;模式匹配参见 正则。 ## 示例 ### 码点、字节与显示单元格
set s "a中c"
echo "chars:" $s(len)                 # 3
echo "bytes:" [bytes/len $s]          # 5
echo "cells:" [width $s]              # 4
### 核心操作
set parts [split "a,b,c" ","]
echo [join $parts " | "]              # a | b | c
echo [upper [trim "  hi  "]]          # HI
echo [replace "foo bar foo" "foo" "baz"]
echo [char-at "a中c" 1]               # 中
echo [index-of "a中b文c" "文"]        # 3
echo [repeat "=" 20]
### 布局:宽度感知的填充、截断与换行
echo [pad-width-right "中文" 8 "-"]         # 中文----
echo [truncate-width "hello world" 8 "…"]   # hello w…
for line [wrap-width "the quick brown fox" 9] {
    echo $line
}
### 字节:二进制数据的原始访问
set blob [bytes/slice "a中c" 0 3]     # 3 raw bytes
echo [byte-at "a中c" 1]               # 228 (0xE4, lead byte of 中)