一個字符串String就是一個字符序列,像”hello,world”,”albatross”這樣的。Swift中的字符串是用String關鍵詞來定義的,同時它也是一些字符的集合,用Character定義。
Swift的String和Character類型為代碼提供了一個快速的,兼容Unicode的字符解決方案。String類型的初始化和使用都是可讀的,并且和C中的strings類似。同時String也可以通過使用+運算符來組合,使用字符串就像使用Swift中的其他基本類型一樣簡單。
1、字符串常量
在代碼中可以使用由String預先定義的字符串常量,定義方式非常簡單:
let someString = “Some string literal value”
字符串常量可以包括下面這些特殊字符:
空字符/0,反斜杠/,制表符/t,換行符/n,回車符/r,雙引號/”和單引號/'
單字節Unicode字符,/xnn,其中nn是兩個十六進制數
雙字節Unicode字符,/unnnn,其中nnnn是四個十六進制數
四字節Unicode字符,/Unnnnnnnn,其中nnnnnnnn是八個十六進制數
下面的代碼給出了這四種字符串的例子:
let wiseWords = "/"Imagination is more important than knowledge/" - Einstein"
// "Imagination is more important than knowledge" - Einstein
let dollarSign = "/x24" // $, Unicode scalar U+0024
let blackHeart = "/u2665" // ♥, Unicode scalar U+2665
let sparklingHeart = "/U0001F496" // , Unicode scalar U+1F496
2、初始化一個空串
初始化一個空串時有兩種形式,但是兩種初始化方法的結果都一樣,表示空串
var emptyString = "" // empty string literal
var anotherEmptyString = String() // initializer syntax
// these two strings are both empty, and are equivalent to each other
通過isEmpty屬性可以檢查一個字符串是否為空
if emptyString.isEmpty {
println("Nothing to see here")
}
// prints "Nothing to see here"
3、變長字符串
如果使用var關鍵詞定義的字符串即為可修改的變長字符串,而let關鍵詞定義的字符串是常量字符串,不可修改。
var variableString = "Horse"
variableString += " and carriage"
// variableString is now "Horse and carriage"
let constantString = "Highlander"
constantString += " and another Highlander"
// this reports a compile-time error - a constant string cannot be modified
4、字符串不是指針,而是實際的值
在Swift中,一個String類型就是一個實際的值,當定義一個新的String,并且將之前的String值拷貝過來的時候,是實際創建了一個相等的新值,而不是僅僅像指針那樣指向過去。
同樣在函數傳遞參數的時候,也是傳遞的實際值,并且創建了一個新的字符串,后續的操作都不會改變原有的String字符串。
5、字符
Swift的字符串String就是由字符Character組成的,每一個Character都代表了一個特定的Unicode字符。通過for-in循環,可以遍歷字符串中的每一個字符:
for character in "Dog!" {
println(character)
}
// D
// o
// g
// !
//
你也可以僅僅定義一個單獨的字符:
let yenSign: Character = "¥"
6、字符計數
使用全局函數countElements可以計算一個字符串中字符的數量:
let unusualMenagerie = "Koala , Snail , Penguin , Dromedary "
println("unusualMenagerie has /(countElements(unusualMenagerie)) characters")
// prints "unusualMenagerie has 40 characters"
7、組合使用字符和字符串
String和Character類型可以通過使用+號相加來組合成一個新的字符串
let string1 = "hello"
let string2 = " there"
let character1: Character = "!"
let character2: Character = "?"
let stringPlusCharacter = string1 + character1 // equals "hello!"
let stringPlusString = string1 + string2 // equals "hello there"
let characterPlusString = character1 + string1 // equals "!hello"
let characterPlusCharacter = character1 + character2 // equals "!?"
也可以使用+=號來組合:
var instruction = "look over"
instruction += string2
// instruction now equals "look over there"
var welcome = "good morning"
welcome += character1
// welcome now equals "good morning!"
8、使用字符串生成新串
通過現有的字符串,可以使用如下方法來生成新的字符串:
let multiplier = 3
let message = "/(multiplier) times 2.5 is /(Double(multiplier) * 2.5)"
// message is "3 times 2.5 is 7.5"
在上面這個例子中,首先使用multiplier這個字符串3,來作為新串的一部分,用(multiplier)添加,同時上面的例子還用到了類型轉換Double(multiplier),將計算結果和字符串本身都作為元素添加到了新的字符串中。
9、字符串比較
Swift提供三種方法比較字符串的值:字符串相等,前綴相等,和后綴相等
字符串相等
當兩個字符串的包含完全相同的字符時,他們被判斷為相等。
let quotation = "We're a lot alike, you and I."
let sameQuotation = "We're a lot alike, you and I."
if quotation == sameQuotation {
println("These two strings are considered equal")
}
// prints "These two strings are considered equal"
//輸出”These two strings are considered equal”
前綴(prefix)相等和后綴(hasSuffix)相等
使用string 類的兩個方法hasPrefix和hasSuffix,來檢查一個字符串的前綴或者后綴是否包含另外一個字符串,它需要一個String類型型的參數以及返回一個布爾類型的值。兩個方法都會在原始字符串和前綴字符串或者后綴字符串之間做字符與字符之間的。
下面一個例子中,用一個字符串數組再現了莎士比亞的羅密歐與朱麗葉前兩幕的場景。
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 方法和romeoAndJuliet數組 計算出第一幕要表演多少個場景。
var act1SceneCount = 0
for scene in romeoAndJuliet {
if scene.hasPrefix("Act 1 ") {
++act1SceneCount
}
}
println("There are /(act1SceneCount) scenes in Act 1")
//輸出”There are 5 scenes in Act 1”
同理,使用hasSuffix 方法去計算有多少個場景發生在Capulet公館和Friar Lawrence牢房
var mansionCount = 0
var cellCount = 0
for scene in romeoAndJuliet {
if scene.hasSuffix("Capulet's mansion") {
++mansionCount
} else if scene.hasSuffix("Friar Lawrence's cell") {
++cellCount
}
}
println("/(mansionCount) mansion scenes; /(cellCount) cell scenes")
// 輸出 "6 mansion scenes; 2 cell scenes”
大小寫字符串
你可以從一個String類型的uppercaseString 和 lowercaseString中獲得一個字符串的大寫或小寫。
let normal = "Could you help me, please?"
let shouty = normal.uppercaseString
// shouty is equal to "COULD YOU HELP ME, PLEASE?"
let whispered = normal.lowercaseString
// whispered is equal to "could you help me, please?"
10、Unicode
Unicode是編碼和表示文本的國際標準。它幾乎可以顯示所有語言的所有字符的標準形態。還可以從類似于文本文件或者網頁這樣的外部源文件中讀取和修改他們的字符。
Unicode術語
每一個Unicode字符都能被編碼為一個或多個unicode scalar。一個unicode scalar是一個唯一的21位數(或者名稱),對應著一個字符或者標識。例如 U+0061是一個小寫的A (“a”), 或者U+1F425是一個面向我們的黃色小雞
當一個Unicode字符串寫入文本或者其他儲存時,unicode scalar會根據Unicode定義的格式來編碼。每一個格式化編碼字符都是小的代碼塊,稱成為code units.他包含UTF-8格式(每一個字符串由8位的code units組成)。和UTF-16格式(每一個字符串由16位的code units組成)
Unicode字符串
Swift 支持多種不同的方式取得Unicode字符串.
你可以使用for-in語句遍歷字符串,來獲得每一個字符的Unicode編碼值。這個過程已經在字符(Working with Characters)描述過了。
或者,下面三個描述中使用合適的一個來獲得一個字符串的值
UTF-8字符編碼單元集合使用String類型的utf-8屬性
UTF-16字符編碼單元集合使用String類型的utf-16屬性
21位Unicode標量集合使用String類型的unicodeScalars屬性
下面的每一個例子展示了不同編碼顯示由 D , o , g , !
(DOG FACE, 或者Unicode標量 U+1F436)字符組成的字符串
UTF-8
你可以使用String類型的utf8屬性遍歷一個UTF-8編碼的字符串。這個屬性是UTF8View類型
,UTF8View是一個8位無符號整形(UInt8)的集合,集合中的每一個字節都是UTF-8編碼。
for codeUnit in dogString.utf8 {
print("/(codeUnit) ")
}
print("/n")
// 68 111 103 33 240 159 144 182
在上面的例子中,前4個十進制codeunit值(68,111,103,33)顯示為字符串 D , o ,g 和 ! ,和他們的ASCII編碼相同一樣。后面4個codeunit的值(240,159,144,182)是DOG FACE字符的4字節UTF-8編碼。
UTF-16
你可以使用String類型的utf16屬性遍歷一個UTF-16編碼的字符串。這個屬性是UTF16View類型,UTF16View是一個16位無符號整形(UInt16)的集合,集合中的每一個字節都是UTF-16編碼。
for codeUnit in dogString.utf16 {
print("/(codeUnit) ")
}
print("/n")
// 68 111 103 33 55357 56374
同理,前4個十進制codeunit值(68,111,103,33)顯示為字符串 D , o ,g 和 ! ,他們的UTF-16 的codeunit和他們UTF-8的編碼值相同。
第5和第6個codeunit值(55357和56374)是DOG FACE字符的UTF-16的代理對編碼。他們的值是由值為U+D83D(十進制55357)的高位代理(lead surrogate)和值為U+DC36 (十進制56374)的低位代理(trail surrogate)組成。
Unicode標量
你可以使用String類型的unicodeScalars屬性遍歷一個Unicode標量編碼的字符串。這個屬性是UnicodeScalarsView類型,UnicodeScalarsView是一個UnicodeScalar類型的集合。每一個Unicode標量都是一個任意21位Unicode碼位,沒有高位代理,也沒有低位代理。
每一個UnicodeScalar使用value屬性,返回標量的21位值,每一位都是32位無符號整形(UInt32)的值:
for scalar in dogString.unicodeScalars {
print("/(scalar.value) ")
}
print("/n")
// 68 111 103 33 128054
value屬性在前4個UnicodeScalar值(68,111,103,33)再一次展示編碼了字符 D , o , g 和 ! 。第五個也是最后一個UnicodeScalar 是DOG FACE字符,十進制為128054,等價于16進制的1F436,相當于Unicode標量的U+1F436。
每一個UnicodeScalar可以被構造成一個新的字符串來代替讀取他們的value屬性,類似于插入字符串。
for scalar in dogString.unicodeScalars { println("/(scalar) ") }
// D
// o
// g
// !
//