Swift 中的字符串操作

Update: Swift 4

  • 字符串截取
var string = "www.stackoverflow.com"

var index = string.index(string.startIndex, offsetBy: 17)
var substring0 = string[string.startIndex..
  • 删除空格
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 转 Int
let string = "123"          // "123"
let intValue = Int(string)  // 123
  • String 转 Double
let string = "3.1415926"          // "3.1415926"
let doubleValue = Double(string)  // 3.1415926

你可能感兴趣的:(Swift 中的字符串操作)