Swift學習筆記(4):字串

來源:互聯網
上載者:User

標籤:分行符號   str   沒有   print   div   gre   聲明   mina   筆記   

目錄:

  • 初始化
  • 常用方法或屬性
  • 字串索引
初始化

建立一個Null 字元串作為初始值:

var emptyString = ""                // Null 字元串字面量var anotherEmptyString = String()   // 初始化方法,兩個字串均為空白並等價。

 

常用方法或屬性
 1 var empty = emptyString.isEmpty    // 判斷字串是否為空白 2 var welcome = "string1" + string2  // 使用 + 或 += 拼接字串 3 welcome.append("character")        // 使用append()在字串末尾追加字元 4  5 // 使用 \(變數) 進行字串插值 6 let multiplier = 3 7 let message = "\(multiplier) times 2.5 is \(Double(multiplier) * 2.5)"  8  9 // 使用 == 或 != 進行字串比較10 if quotation == sameQuotation {11     print("These two strings are considered equal")12 }13 14 // 使用 hasPrefix() 和 hasSuffix() 判斷是否又首碼或尾碼15 if scene.hasPrefix("Act 1 ") {16     print("The string has the prefix of Act 1“)17 }

注意:

?不能將一個字串或者字元添加到一個已經存在的字元變數上,因為字元變數只能包含一個字元。
?插值字串中寫在括弧中的運算式不能包含非轉義反斜線 ( \ ),並且不能包含斷行符號或分行符號。

 

字串索引

可以通過字串下標或索引屬性和方法來訪問和修改它,String.Index對應著字串中的Character位置。

 1 sampleString.startIndex.         // 擷取第一個字元的索引     2 sampleString.endIndex            // 擷取最後一個字元的索引 3  4 let greeting = "Guten Tag!" 5 greeting[greeting.startIndex]    // G 使用下標擷取字元 6 greeting[greeting.index(before: greeting.endIndex)]   // ! 7 greeting[greeting.index(after: greeting.startIndex)]  // u 8  9 let index = greeting.index(greeting.startIndex, offsetBy: 7)10 greeting[index]                                       // a11 12 /* 13     greeting[greeting.endIndex]        // error Index越界14     greeting.index(after: endIndex)    // error Index越界15 */16 17 // 使用 characters.indices 屬性建立一個包含全部索引Range來遍曆字串中單個字元18 for index in greeting.characters.indices {19     print("\(greeting[index]) ", terminator: "") // 輸出 "G u t e n T a g ! "20 }21 22 var welcome = "hello"23 welcome.insert("!", at: welcome.endIndex)        // welcome 等於 "hello!"24 welcome.remove(at: welcome.index(before: welcome.endIndex))// welcome 等於 "hello"

 

注意:

?可擴充的字元群集可以組成一個或者多個Unicode標量。這意味著不同的字元以及相同字元的不同表示方式可能需要不同數量的記憶體空間來儲存。所以Swift中的字元在一個字串中並不一定佔用相同的記憶體空間。因此在沒有獲得字串可擴充字元群集範圍的時候,是不能計算出字串的字元數量,此時就必須遍曆字串全部的 Unicode 標量,來確定字元數量。

 

聲明:該系列內容均來自網路或電子書籍,只做學習總結!

Swift學習筆記(4):字串

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.