var str = “Hello world" for s in str.characters { print(s) }
var str = “Hello world你好" // 返回以字节为单位的字符串长度,一个中文占 3 个字节 17 let len1 = str.lengthOfBytesUsingEncoding(using: .utf8) // 返回实际字符的个数 13 let len2 = str.characters.count // 使用 NSString 跳转 // Swift 中可以使用 值 as 类型 来进行类型强转 // Swift 中, 除 String 之外, 绝大多数使用 as 需要 ? / ! // as! / as? 直接根据前面返回的值来决定 // 注意: if let / if guard 判空语句, 一律使用 as? let ocStr = str as NSString print(ocStr.length)
let str1 = "Hello" let str2 = "World" let i = 32 str = "\(i) 个 " + str1 + " " + str2
let str1 = "Hello" let str2 = "World" let i: Int? = 32 str = "\(i ?? 0) 个 " + str1 + " " + str2
let h = 8 let m = 23 let s = 9 let timeString = String(format: "%02d:%02d:%02d", arguments: [h, m, s]) let timeStr = String(format: "%02d:%02d:%02d", h, m, s)
let helloString = "我们一起飞" (helloString as NSString).substringWithRange(NSMakeRange(2, 3))
// 建议:一般使用 NSString 作为中转,因为 Swift 取子串的方法一直在优化 let str = “我们一起去飞" // 1. NSString let ocStr = str as NSString let s1 = ocStr.substring(with: NSMakeRange(2, 3)) print(s1) // 2. String 的方法 let s2 = str.substring(from: “我们”.endIndex) print(s2) let s3 = str.substring(from: “abc”.endIndex) print(s3) // 取子串的范围 guard let range = str.range(of: “一起”) else { print(“没有找到字符串") return } // 一定找到的范围 print(range) print(str.substring(with: range))
原文:http://www.cnblogs.com/fanxiaocong/p/6411286.html