Swift String 与 NSString


NSString 与 String 之间可以随意转换

"hello".characters.count // 5
"你好".characters.count // 2

如果想知道在某个编码下占多少字节, 可以用

let simpleString = "Hello, world"
simpleString.substring(to: simpleString.index(simpleString.startIndex, offsetBy: 5))
// hello
simpleString.substring(from: simpleString.index(simpleString.endIndex, offsetBy: -5))
// world
simpleString.substring(with: simpleString.index(simpleString.startIndex, offsetBy: 5) ..< simpleString.index(simpleString.endIndex, offsetBy: -5))
// ,