【Swift】學習筆記(三)——字元和字串

來源:互聯網
上載者:User

標籤:方法   style   div   bsp   ...   推斷   返回   ref   基本   

基本瞭解了變數的建立和基礎資料類型,但是在開發中用得最多的還是字串。那什麼是字串呢?


Swift 的String類型表示特定序列的Character(字元) 類型值的集合,它是實值型別具有可變性

Swift 的字串和字元類型是全然相容 Unicode 標準的

1、定義一個String類型變數

let stringTest = "String test"   //定義一個stringTest String類型變數 其值為String testlet stringTest: String = "String test"   //和上面意思一樣let stringTest = String()        //定義一個stringTest String類型變數 其值為空白字串let stringTest = ""              //同上


也能夠通過插值的方式:\()

let inta = 1

let stringTest = "\(inta)"


注意插值方式不能包括 “ 和 \ 而且不能包括斷行符號或換行


2、字串操作 +

let stringTest = "my test "

stringTest += "you test"    //stringTest的值為my test you test


也能夠用+操作字元,比如 

let stringTest = "my test"

let chaTest: Character = "y"

let result = stringTest + chaTest      //值為 my testy


3、字串比較

因為它是實值型別,那就簡單啦 用 ==  就可以。

還能夠比較字串的首碼或者尾碼相等:hasPrefix/hasSuffix


4、字串字面量

let stringTest = "my test"   //當中"my test"就是一個字面量

字串字面量能夠包括下面特殊字元:

逸出字元\0(Null 字元)、\\(反斜線)、\t(水平定位字元)、\n(分行符號)、\r(斷行符號符)、\"(雙引號)、\‘(單引號)。
單位元組 Unicode 標量,寫成\xnn,當中nn為兩位十六進位數。
雙位元組 Unicode 標量,寫成\unnnn,當中nnnn為四位十六進位數。
四位元組 Unicode 標量。寫成\Unnnnnnnn,當中nnnnnnnn為八位十六進位數。



5、字串函數介紹

a 推斷字串是否為空白  stringTest.isEmpty  這是個屬性 返回Bool值

b 推斷字串長度 全域函數 countElements比如countElemets(stringTest)

c hasPrefix/hasSuffix方法來檢查字串是否擁有特定首碼/尾碼比如 let stringTest = "abc_123";stringTest.hasPrefix("abc")    //將返回true

d uppercaseString和lowercaseString屬性來訪問大寫/小寫版本號碼的字串

...還有非常多




【Swift】學習筆記(三)——字元和字串

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.