Swift的String類型是用Foundation的NSString類來橋接的。 Foundation還擴展了String以公開NSString定義的方法。 這意味著,如果您導入Foundation,則可以在String上訪問這些NSString方法,而不進行轉換。
初始化字符串
var emptyString = "" // empty string literal
var anotherEmptyString = String() // initializer syntax
// these two strings are both empty, and are equivalent to each other
判斷字符串是否為空
if emptyString.isEmpty {
print("Nothing to see here")
}
// Prints "Nothing to see here"
可變字符串
您可以指定特定的字符串是否可以通過將其賦值給變量(在這種情況下可以修改)或常量(在這種情況下不能修改)來決定是否修改(或改變):
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
這種方法不同于Objective-C和Cocoa中的字符串變量,您可以在兩個類(NSString和NSMutableString)之間進行選擇,以指示字符串是否可以進行改變。
字符串是值類型
Swift的String類型是一個值類型。 如果創建一個新的字符串值,那么該字符串值在傳遞給函數或方法時或者在賦給常量或變量時被復制。 在每種情況下,將創建現有String值的新副本,并傳遞或分配新副本,而不是原始版本。
Swift的按默認值復制String的行為確保當一個函數或方法傳遞一個String值時,很明顯你擁有該精確的String值,而不管它來自哪里。 您可以確信,您傳遞的字符串不會被修改,除非您自己修改它。
字符
您可以通過使用for-in循環遍歷其字符屬性來訪問字符串的各個字符值:
for character in "Dog!??".characters {
print(character)
}
// D
// o
// g
// !
// ??
或者,您可以通過提供字符類型注釋,從單字符字符串文字創建獨立的字符常量或變量:
let exclamationMark: Character = "!"
可以通過將字符值數組作為參數傳遞給它的初始化器來構造字符串值:
let catCharacters: [Character] = ["C", "a", "t", "!", "??"]
let catString = String(catCharacters)
print(catString)
// Prints "Cat!??"
拼接字符串和字符
字符串值可用加法運算符(+)一起添加(或連接),以創建新的字符串值:
let string1 = "hello"
let string2 = " there"
var welcome = string1 + string2
// welcome now equals "hello there"
您還可以使用附加賦值運算符(+ =)將String值附加到現有的String變量:
var instruction = "look over"
instruction += string2
// instruction now equals "look over there"
您可以使用String類的append()方法將Character值拼接到String變量:
let exclamationMark: Character = "!"
welcome.append(exclamationMark)
// welcome now equals "hello there!"
注意:您不能將字符串或字符附加到現有的字符變量,因為字符值只能包含一個字符。
字符串插入
字符串插值是通過將常量,變量,文字和表達式的值包含在字符串文字中來從常量,變量,文字和表達式的混合構造新的String值的一種方法。 您插入到字符串文字中的每個項都包含在一對括號中,前綴為反斜杠:
let multiplier = 3
let message = "\(multiplier) times 2.5 is \(Double(multiplier) * 2.5)"
// message is "3 times 2.5 is 7.5"
在插入字符串中的括號內寫入的表達式不能包含未轉義的反斜杠(\),回車或換行符。 但是,它們可以包含其他字符串文字。
字符串字面量中的特殊字符
字符串文字可以包含以下特殊字符:
- 轉義的特殊字符\ 0(空字符),\(反斜杠),\ t(水平制表符),\ n(換行),\ r(回車) )
- 任意Unicode標量,寫為\ u {n},其中n是一個1-8位的十六進制數,值等于有效的Unicode代碼點
let wiseWords = "\"Imagination is more important than knowledge\" - Einstein"
// "Imagination is more important than knowledge" - Einstein
let dollarSign = "\u{24}" // $, Unicode scalar U+0024
let blackHeart = "\u{2665}" // ?, Unicode scalar U+2665
let sparklingHeart = "\u{1F496}" // ??, Unicode scalar U+1F496
計數字符
要檢索字符串中的字符值的計數,請使用字符串的characters屬性的count屬性:
let unusualMenagerie = "Koala ??, Snail ??, Penguin ??, Dromedary ??"
print("unusualMenagerie has \(unusualMenagerie.characters.count) characters")
// Prints "unusualMenagerie has 40 characters"
訪問和修改字符串
- 您可以通過其方法和屬性或通過使用下標語法來訪問和修改字符串。
- 每個String值都有一個相關的索引類型String.Index,它對應于字符串中每個字符的位置。
- 如上所述,不同的字符可能需要不同數量的內存來存儲,因此為了確定哪個字符在特定位置,您必須從該字符串的開頭或結尾遍歷每個Unicode標量。 因此,Swift字符串不能用整數值索引。
- 使用startIndex屬性訪問字符串的第一個字符的位置。 endIndex屬性是字符串中最后一個字符之后的位置。 因此,endIndex屬性不是字符串下標的有效參數。 如果String為空,startIndex和endIndex相等。
- 使用String的index(before :)和index(after :)方法之前,可以訪問給定索引前后的索引。 要訪問遠離給定索引的索引,可以使用索引(_:offsetBy :)方法,而不是多次調用這些方法。
- 您可以使用下標語法來訪問特定String索引處的字符。
let greeting = "Guten Tag!"
greeting[greeting.startIndex]
// G
greeting[greeting.index(before: greeting.endIndex)]
// !
greeting[greeting.index(after: greeting.startIndex)]
// u
let index = greeting.index(greeting.startIndex, offsetBy: 7)
greeting[index]
// a
使用characters屬性的indices屬性訪問字符串中各個字符的所有索引。
for index in greeting.characters.indices {
print("\(greeting[index]) ", terminator: "")
}
// Prints "G u t e n T a g ! "
注意:您可以在符合Collection協議的任何類型上使用startIndex和endIndex屬性和索引(before :),index(after :)和index(_:offsetBy :)方法。 這包括String,如下所示,以及集合類型,如Array,Dictionary和Set。
插入和刪除
要在指定索引處將單個字符插入到字符串中,請使用insert(_:at :)方法,并在指定索引處插入另一個字符串的內容,請使用insert(contents Of:a :)方法。
var welcome = "hello"
welcome.insert("!", at: welcome.endIndex)
// welcome now equals "hello!"
welcome.insert(contentsOf:" there".characters, at: welcome.index(before: welcome.endIndex))
// welcome now equals "hello there!"
要從指定索引的字符串中刪除單個字符,請使用remove(at :)方法,并刪除指定范圍內的子字符串,請使用removeSubrange(_ :)方法:
welcome.remove(at: welcome.index(before: welcome.endIndex))
// welcome now equals "hello there"
let range = welcome.index(welcome.endIndex, offsetBy: -6)..<welcome.endIndex
welcome.removeSubrange(range)
// welcome now equals "hello"
注意:您可以在符合RangeReplaceableCollection協議的任何類型上使用insert(:at :),insert(contentsOf:at :),remove(at :)和removeSubrange( :)方法。 這包括String,以及集合類型,如Array,Dictionary和Set。
比較字符串
Swift提供了三種比較文本值的方法:字符串和字符相等,前綴相等和后綴相等。
字符串和字符相等
字符串和字符相等性通過“等于”運算符(==)和“不等于”運算符(!=)進行檢查。
let quotation = "We're a lot alike, you and I."
let sameQuotation = "We're a lot alike, you and I."
if quotation == sameQuotation {
print("These two strings are considered equal")
}
// Prints "These two strings are considered equal"
前綴和后綴相等
要檢查字符串是否有特定的字符串前綴或后綴,請調用字符串的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"
]
你可以使用haseprefix(_ :)方法和romeoAndJuliet數組來計算播放的Act 1中的場景數量:
var act1SceneCount = 0
for scene in romeoAndJuliet {
if scene.hasPrefix("Act 1 ") {
act1SceneCount += 1
}
}
print("There are \(act1SceneCount) scenes in Act 1")
// Prints "There are 5 scenes in Act 1"
注意:hasPrefix(_ :)和hasSuffix(_ :)方法在每個字符串中的擴展字形集群之間執行逐個字符的規范等價比較,如字符串和字符平等中所述。
字符串的Unicode表示形式
使用三種其他符合Unicode的表示之一訪問字符串值:
- 一組UTF-8代碼單元(使用字符串的utf8屬性訪問)
- 一組UTF-16代碼單元(使用字符串的utf16屬性訪問)
- 21位Unicode標量值的集合,等同于字符串的UTF-32編碼形式(使用字符串的unicodeScalars屬性訪問)