示例工程 03-strings-unicode
另有 1 个文件未随站点发布(平台工程、二进制或超过 200KB)。
03-strings-unicode/Sources/Ch03Kit/StringIndexLab.swift
/// `String.Index` 不是整数:按字符截断与按字节截断的结果不同。
public enum StringIndexLab {
/// 按字素簇截断,不会切开 emoji 或组合字符。
public static func prefixCharacters(_ text: String, count: Int) -> String {
String(text.prefix(count))
}
/// 按 UTF-8 字节截断;切在码点中间时会产生替换字符 U+FFFD。
public static func prefixBytes(_ text: String, count: Int) -> String {
String(decoding: text.utf8.prefix(count), as: UTF8.self)
}
/// 每个字素簇起始处的 UTF-8 字节偏移。
public static func byteOffsets(_ text: String) -> [Int] {
text.indices.map { text.utf8.distance(from: text.utf8.startIndex, to: $0) }
}
/// 用 `index(_:offsetBy:)` 定位,再取一个合法范围。
public static func slice(_ text: String, from start: Int, length: Int) -> String {
guard start >= 0, length >= 0, start + length <= text.count else { return "" }
let lower = text.index(text.startIndex, offsetBy: start)
let upper = text.index(lower, offsetBy: length)
return String(text[lower..<upper])
}
}