Update: Swift 4
- 字符串截取
var string = "www.stackoverflow.com"
var index = string.index(string.startIndex, offsetBy: 17)
var substring0 = string[string.startIndex..<index] // www.stackoverflow
var substring1 = string[index..<string.endIndex] // .com
// 或(Swift4 新增语法糖)
var substring2 = string[..<index] // www.stackoverflow
var substring3 = string[index...] // .com
var substring4 = string[string.index(string.startIndex, offsetBy: 4)..<index] // stackoverflow
// 掐头去尾
let substring5 = String(string.characters.dropFirst(4)) // stackoverflow.com
let substring6 = String(string.characters.dropLast(4)) // www.stackoverflow
- 删除空格
var string = " www.stackoverflow.com "
// 删除两端空格
string.trimmingCharacters(in: CharacterSet.whitespaces)
// 删除两端空格和换行符
string.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines)
- 范围替换
var string = "www.stackoverflow.com"
let range = string.index(string.startIndex, offsetBy: 4)..<string.index(string.endIndex, offsetBy: -4)
string.replaceSubrange(range, with: "segmentfault") // www.segmentfault.com
- String 转 Int
let string = "123" // "123"
let intValue = Int(string) // 123
- String 转 Double
let string = "3.1415926" // "3.1415926"
let doubleValue = Double(string) // 3.1415926