OC 定義字符 char charValue = 'a';
Swift 定義字符 var charValue:Character = "a"
Unicode 國際標準的文本編碼 他幾乎能夠表示全部國家字符
OC能夠存儲ASCII字符 Swift能夠存ASCII+Unicodeswift
var charValue:Character = "🐶" var charValue2:Character = "旭" //var charValue3:Character = "旭旭" 錯誤 字符!!! print(charValue) print(charValue2)
字符串是能夠存不少字符的集合ui
OC NSString * str = @"旭旭"; Swift let str:String = "旭旭"
OC -> @""
Swift -> ""編碼
String -> NSString (Swift->OC)
let str:NSString = NSString(string:"旭旭")code
OC 以\0爲結束
Swift 不是以\0爲結束orm
初始化字符串字符串
let emptyString = "" let emptyString2 = String()
遍歷字符串string
let string = "lalala" for a in string.characters{ print(a) }
獲取字符串的長度it
let count = string.characters.count print(count)
判斷字符串是否爲空io
let emptyStr = "" if emptyStr.isEmpty{ print("YES") }
字符串的拼接form
let str1 = "lala" let str2 = "kaka" let result = str1 + str2 print(result)
格式化字符串
let str1 = "愛" let str2 = "旭寶\(str1)吃魚" print(str2)
取小數後兩位
let pi = 3.141592653 let str = String(format: "%.2f",pi) print(str)
字符串比較
let str1 = "abc" let str2 = "abc" if str1 == str2 { print("相等") }
查詢先後綴
let str = "www.baidu.com" if str.hasPrefix("www"){ } if str.hasSuffix("com"){ }
大小寫
let str = "www.baidu.com" let str1 = str.uppercaseString let str2 = str.lowercaseString print(str1) print(str2)
String轉基本數據類型
//輸出爲可選類型 由於有可能不成功 let str = "5.2" let num = Float(str12) print(num)
截取字符串
let str = "qwertyuiop" let toStr = str.startIndex.advancedBy(2) //從0開始跑 let str1 = str.substringToIndex(toStr) print(str1)
let str = "qwertyuiop" let toStr = str.endIndex.advancedBy(-2) let str1 = str.substringToIndex(toStr) print(str1)
let str = "qwertyuiop" let fromStr = str.startIndex.advancedBy(2) let toStr = str.endIndex.advancedBy(-2) let range:Range <String.Index> = Range(start:fromStr,end:toStr)//swift 3廢棄 let str1 = str.substringWithRange(range) print(str1)
let str = "qwertyuiop" let toStr = (str as NSString).substringToIndex(2) print(toStr)
let str = "qwertyuiop" let range = NSRange(location: 2,length: 5) let toStr = (str as NSString).substringWithRange(range) print(toStr)