學習swift的String用法總結
學習了swift的String的用法之后感覺比OC的太直接了,不需要直接的初始化、類型聲明也不用區分可變和不可變的類型,基本上就是屬於哪里需要就在哪里直接寫就可以的狀態。
override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib.
print("viewDidLoad")
//字符串 //初始化空字符串
let emptyString = "" // 空字符串字面量
let anotherEmptyString = String() // 初始化方法 // 兩個字符串均為空並等價。
if emptyString.isEmpty && anotherEmptyString.isEmpty { print("Nothing to see here") } // 打印輸出:"Nothing to see here" //字符串可以通過傳遞一個值類型為Character的數組作為自變量來初始化
let catCharacters: [Character] = ["C", "a", "t", "!", "🐱"] let catString = String(catCharacters) print(catString)// 打印輸出:"Cat!🐱" //數值型字符串轉化為數值
let numberOfStr = "123.6" let convertedNumber = Double(numberOfStr)//將數值型字符串 轉化為數值
print("stringValue:'\(numberOfStr)\' convertedNumberValue:\(convertedNumber!)")//打印 stringValue:'123.6' convertedNumberValue:123.6 //字符串的遍歷
let randomString = "hello everybody"
for char in randomString.characters{ print("The results of the ergodic:\(char)") /*打印 The results of the ergodic:h The results of the ergodic:e The results of the ergodic:l The results of the ergodic:l The results of the ergodic:o The results of the ergodic: The results of the ergodic:e The results of the ergodic:v The results of the ergodic:e The results of the ergodic:r The results of the ergodic:y The results of the ergodic:b The results of the ergodic:o The results of the ergodic:d The results of the ergodic:y*/ } //字符串拼接
let str1 = "hello " let str2 = "word" var str = "" str = str1 + str2//字符串拼接
print("The joining together of two strings:\(str)")//打印 The joining together of two strings:hello word
let exclamationMark:Character = "!" str.append(exclamationMark)//將一個字符串添加到另一個字符串的尾部
print("使用append拼接一個字符:\(str)")//打印 使用append拼接一個字符:hello word!
let subStr = "word" str.append(subStr) print("使用append拼接一個子字符串:\(str)")//打印 使用append拼接一個子字符串:hello word!word //字符串插值
let addend = 6 let sumStr = "\(addend) add 8.1 is \(Double(addend) + 8.1)" print(sumStr)//打印 6 add 8.1 is 14.1 //字符串字面量的特殊字符
let dollarSign = "\u{24}" // $, Unicode 標量 U+0024
let blackHeart = "\u{2665}" // ♥, Unicode 標量 U+2665
let sparklingHeart = "\u{1F496}" // 💖, Unicode 標量 U+1F496
print(dollarSign,blackHeart,sparklingHeart)//打印 $ ♥ 💖 //可擴展的字形群集
let eAcute: Character = "\u{E9}" // é
let combinedEAcute: Character = "\u{65}\u{301}" // e 后面加上 ́ // eAcute 是 é, combinedEAcute 是 é
print("eAcuteValue:\(eAcute),combinedEAcuteValue:\(combinedEAcute)")//打印 eAcuteValue:é,combinedEAcuteValue:é //字符串的索引 //可擴展的字符群集可以組成一個或者多個 Unicode 標量。這意味着不同的字符以及相同字符的不同表示方式可能需要不同數量的內存空間來存儲。所以 Swift 中的字符在一個字符串中並不一定占用相同的內存空間數量。因此在沒有獲取字符串的可擴展的字符群的范圍時候,就不能計算出字符串的字符數量。如果您正在處理一個長字符串,需要注意characters屬性必須遍歷全部的 Unicode 標量,來確定字符串的字符數量。 //另外需要注意的是通過characters屬性返回的字符數量並不總是與包含相同字符的NSString的length屬性相同。NSString的length屬性是利用 UTF-16 表示的十六位代碼單元數字,而不是 Unicode 可擴展的字符群集。 //前面提到,不同的字符可能會占用不同數量的內存空間,所以要知道Character的確定位置,就必須從String開頭遍歷每一個 Unicode 標量直到結尾。因此,Swift 的字符串不能用整數(integer)做索引。 //使用startIndex屬性可以獲取一個String的第一個Character的索引。使用endIndex屬性可以獲取最后一個Character的后一個位置的索引。因此,endIndex屬性不能作為一個字符串的有效下標。如果String是空串,startIndex和endIndex是相等的。 //通過調用 String 的 index(before:) 或 index(after:) 方法,可以立即得到前面或后面的一個索引。您還可以通過調用 index(_:offsetBy:) 方法來獲取對應偏移量的索引,這種方式可以避免多次調用 index(before:) 或 index(after:) 方法。
let stringIndexStr = "hello word!" let starIndexC = stringIndexStr[stringIndexStr.startIndex]//獲取字符串第一個索引的 字符
print("startIndexValue:\(stringIndexStr.startIndex)")//打印 startIndexValue:Index(_base: Swift.String.UnicodeScalarView.Index(_position: 0), _countUTF16: 1)
print("starIndexCharacter:\(starIndexC)")//打印 starIndexCharacter:h //endIndex屬性不能作為一個字符串的有效下標,運行時會崩潰 //let endIndexC = stringIndexStr[stringIndexStr.endIndex]//試圖獲取越界索引對應的 Character,將引發一個運行時錯誤。 //print("endIndexCharacter:\(endIndexC)")
let afterIndexC = stringIndexStr[stringIndexStr.index(after: stringIndexStr.startIndex)]//獲取字符串 第二個索引的字符(第一個索引后面的一個索引值)
print(afterIndexC)//打印 e
let beforeIndexC = stringIndexStr[stringIndexStr.index(before: stringIndexStr.endIndex)]//獲取字符串末尾的一個字符(最后一個索引前面的一個索引,使用endIndex屬性可以獲取最后一個Character的后一個位置的索引,endIndex屬性不能作為一個字符串的有效下標)
print(beforeIndexC)//打印 !
let offSetByIndex = stringIndexStr.index(stringIndexStr.startIndex, offsetBy: 4)//第一個索引4個偏移量之后的一個索引
print(offSetByIndex,stringIndexStr[offSetByIndex])//打印 Index(_base: Swift.String.UnicodeScalarView.Index(_position: 4), _countUTF16: 1) o //字符串的插入和刪除 //字符串插入
var welcome = "hello" welcome.insert("!", at: welcome.endIndex)//插入一個字符
print("insertNewCharacters:\(welcome)\n");//打印 insertNewCharacters:hello!
welcome.insert(contentsOf: " word".characters, at: welcome.index(before: welcome.endIndex))//插入一個子字符串
print("insertNewSubStr:\(welcome)\n")//打印 insertNewSubStr:hello word! //字符串刪除
welcome.remove(at: welcome.index(before: welcome.endIndex))//刪除最后一個字符
print("removeStrLastCharacters:\(welcome)\n")//打印 removeStrLastCharacters:hello word
let range = welcome.index(welcome.endIndex, offsetBy: -6)..<welcome.endIndex welcome.removeSubrange(range)//刪除規定范圍內的子串
print("removeStrRange:\(welcome)\n")//打印 removeStrRange:hell //字符串的比較(Swift 提供了三種方式來比較文本值:字符串字符相等、前綴相等和后綴相等。)
let quotation = "We're a lot alike, you and I." let sameQuotation = "We're a lot alike, you and I."
if quotation == sameQuotation {//如果兩個字符串(或者兩個字符)的可擴展的字形群集是標准相等的,那就認為它們是相等的。在這個情況下,即使可擴展的字形群集是有不同的 Unicode 標量構成的,只要它們有同樣的語言意義和外觀,就認為它們標准相等。(例如,LATIN SMALL LETTER E WITH ACUTE(U+00E9)就是標准相等於LATIN SMALL LETTER E(U+0065)后面加上COMBINING ACUTE ACCENT(U+0301)。這兩個字符群集都是表示字符é的有效方式,所以它們被認為是標准相等的:)
print("These two strings are considered equal") } // 打印輸出 "These two strings are considered equal" //相反,英語中的LATIN CAPITAL LETTER A(U+0041,或者A)不等於俄語中的CYRILLIC CAPITAL LETTER A(U+0410,或者A)。兩個字符看着是一樣的,但卻有不同的語言意義:
let latinCapitalLetterA: Character = "\u{41}" let cyrillicCapitalLetterA: Character = "\u{0410}"
if latinCapitalLetterA != cyrillicCapitalLetterA { print("These two characters are not equivalent") } // 打印 "These two characters are not equivalent" //前綴/后綴相等
let romeoAndJuliet = [ "Act 1 Scene 1: Verona, A public place", "Act 1 Scene 2: Capulet's mansion", "Act 1 Scene 3: A room in Capulet's mansion", "Act 1 Scene 4: A street outside Capulet's mansion", "Act 1 Scene 5: The Great Hall in Capulet's mansion", "Act 2 Scene 1: Outside Capulet's mansion", "Act 2 Scene 2: Capulet's orchard", "Act 2 Scene 3: Outside Friar Lawrence's cell", "Act 2 Scene 4: A street in Verona", "Act 2 Scene 5: Capulet's mansion", "Act 2 Scene 6: Friar Lawrence's cell" ] //可以調用hasPrefix(_:)方法來計算話劇中第一幕的場景數:(遍歷查找前綴相等)
var act1SceneCount = 0
for scene in romeoAndJuliet { if scene.hasPrefix("Act 1 ") { act1SceneCount += 1 } } print("There are \(act1SceneCount) scenes in Act 1") // 打印輸出 "There are 5 scenes in Act 1" //可以用hasSuffix(_:)方法來計算發生在不同地方的場景數:(后綴相等)
var mansionCount = 0 var cellCount = 0
for scene in romeoAndJuliet { if scene.hasSuffix("Capulet's mansion") { mansionCount += 1 } else if scene.hasSuffix("Friar Lawrence's cell") { cellCount += 1 } } print("\(mansionCount) mansion scenes; \(cellCount) cell scenes") // 打印輸出 "6 mansion scenes; 2 cell scenes" //hasPrefix(_:)和hasSuffix(_:)方法都是在每個字符串中逐字符比較其可擴展的字符群集是否標准相等
}