Xcode 8.0 Swift 3.0 字符串操作
// 定义一个字符串
let str = "这是字符串"
// 1.打印字符串长度
print(str.characters.count)
// 2.打印UTF8编码字节数
print(str.utf8.count)
print(str.lengthOfBytes(using: String.Encoding.utf8))
// 3.字符串遍历
for value in str.characters {
print(value);
}
// 4.字符串拼接
let name = "老王",age = 20
let s1 = "名字是" + name + ",年龄是" + String(age)
print(s1)
let s2 = "名字是\(name),年龄是\(age)"
print(s2)
// 5.格式化字符串输入
let h = 9, m = 50, s = 45
let time = String(format: "%02d:%02d:%02d", h, m, s)
print(time)
let time2 = String(format: "%02d:%02d:%02d", arguments: [h, m, s])
print(time2)
// 6.字符串截取
// let r1 = "名字是老王,年龄是20"
// startIndex 开始的位置
// offsetBy 偏移的字符数
let index = s1.index(s1.startIndex, offsetBy: 2)
// 从指定位置开始,到字符串结尾
let r1 = s1.substring(from: index)
print(r1)
// endIndex 结束位置
let index2 = s1.index(s2.endIndex, offsetBy: -2)
// to 从字符开始位置到指定位置结束
let r2 = s1.substring(to: index2)
print(r2)
// range 范围
let range = index..<index2
let r3 = s1.substring(with: range)
print("range\(r3)")
// 7.将swift 字符串 转换为 OC 字符串
let OCString = (s2 as NSString)
let os = OCString.substring(with: NSMakeRange(2, 4))
print(os)
let os1 = OCString.substring(from: 2)
print(os1)
let os2 = OCString.substring(to: 5)
print(os2)