Swift的String類型是用Foundation的NSString類來橋接的。 Foundation還擴展了String以公開NSString定義的方法龙填。 這意味著,如果您導入Foundation,則可以在String上訪問這些NSString方法,而不進行轉(zhuǎn)換皆的。
初始化字符串
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類型是一個值類型内狗。 如果創(chuàng)建一個新的字符串值怪嫌,那么該字符串值在傳遞給函數(shù)或方法時或者在賦給常量或變量時被復制。 在每種情況下柳沙,將創(chuàng)建現(xiàn)有String值的新副本岩灭,并傳遞或分配新副本,而不是原始版本赂鲤。
Swift的按默認值復制String的行為確保當一個函數(shù)或方法傳遞一個String值時噪径,很明顯你擁有該精確的String值柱恤,而不管它來自哪里。 您可以確信找爱,您傳遞的字符串不會被修改梗顺,除非您自己修改它。
字符
您可以通過使用for-in循環(huán)遍歷其字符屬性來訪問字符串的各個字符值:
for character in "Dog!??".characters {
print(character)
}
// D
// o
// g
// !
// ??
或者车摄,您可以通過提供字符類型注釋寺谤,從單字符字符串文字創(chuàng)建獨立的字符常量或變量:
let exclamationMark: Character = "!"
可以通過將字符值數(shù)組作為參數(shù)傳遞給它的初始化器來構(gòu)造字符串值:
let catCharacters: [Character] = ["C", "a", "t", "!", "??"]
let catString = String(catCharacters)
print(catString)
// Prints "Cat!??"
拼接字符串和字符
字符串值可用加法運算符(+)一起添加(或連接),以創(chuàng)建新的字符串值:
let string1 = "hello"
let string2 = " there"
var welcome = string1 + string2
// welcome now equals "hello there"
您還可以使用附加賦值運算符(+ =)將String值附加到現(xiàn)有的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!"
注意:您不能將字符串或字符附加到現(xiàn)有的字符變量吮播,因為字符值只能包含一個字符变屁。
字符串插入
字符串插值是通過將常量,變量意狠,文字和表達式的值包含在字符串文字中來從常量粟关,變量,文字和表達式的混合構(gòu)造新的String值的一種方法环戈。 您插入到字符串文字中的每個項都包含在一對括號中闷板,前綴為反斜杠:
let multiplier = 3
let message = "\(multiplier) times 2.5 is \(Double(multiplier) * 2.5)"
// message is "3 times 2.5 is 7.5"
在插入字符串中的括號內(nèi)寫入的表達式不能包含未轉(zhuǎn)義的反斜杠(\),回車或換行符院塞。 但是蛔垢,它們可以包含其他字符串文字。
字符串字面量中的特殊字符
字符串文字可以包含以下特殊字符:
- 轉(zhuǎn)義的特殊字符\ 0(空字符)迫悠,\(反斜杠)鹏漆,\ t(水平制表符),\ n(換行)创泄,\ r(回車) )
- 任意Unicode標量艺玲,寫為\ u {n},其中n是一個1-8位的十六進制數(shù)鞠抑,值等于有效的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
計數(shù)字符
要檢索字符串中的字符值的計數(shù)饭聚,請使用字符串的characters屬性的count屬性:
let unusualMenagerie = "Koala ??, Snail ??, Penguin ??, Dromedary ??"
print("unusualMenagerie has \(unusualMenagerie.characters.count) characters")
// Prints "unusualMenagerie has 40 characters"
訪問和修改字符串
- 您可以通過其方法和屬性或通過使用下標語法來訪問和修改字符串。
- 每個String值都有一個相關(guān)的索引類型String.Index搁拙,它對應于字符串中每個字符的位置秒梳。
- 如上所述,不同的字符可能需要不同數(shù)量的內(nèi)存來存儲箕速,因此為了確定哪個字符在特定位置酪碘,您必須從該字符串的開頭或結(jié)尾遍歷每個Unicode標量。 因此盐茎,Swift字符串不能用整數(shù)值索引兴垦。
- 使用startIndex屬性訪問字符串的第一個字符的位置。 endIndex屬性是字符串中最后一個字符之后的位置。 因此探越,endIndex屬性不是字符串下標的有效參數(shù)狡赐。 如果String為空,startIndex和endIndex相等钦幔。
- 使用String的index(before :)和index(after :)方法之前枕屉,可以訪問給定索引前后的索引。 要訪問遠離給定索引的索引鲤氢,可以使用索引(_:offsetBy :)方法搀庶,而不是多次調(diào)用這些方法。
- 您可以使用下標語法來訪問特定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協(xié)議的任何類型上使用startIndex和endIndex屬性和索引(before :),index(after :)和index(_:offsetBy :)方法揍庄。 這包括String咆蒿,如下所示,以及集合類型蚂子,如Array沃测,Dictionary和Set。
插入和刪除
要在指定索引處將單個字符插入到字符串中食茎,請使用insert(_:at :)方法蒂破,并在指定索引處插入另一個字符串的內(nèi)容,請使用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 :)方法,并刪除指定范圍內(nèi)的子字符串哎媚,請使用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協(xié)議的任何類型上使用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"
前綴和后綴相等
要檢查字符串是否有特定的字符串前綴或后綴钱床,請調(diào)用字符串的hasPrefix(_ :)和hasSuffix(_ :)方法荚斯,它們都接受一個類型為String的參數(shù)埠居,并返回一個布爾值查牌。
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數(shù)組來計算播放的Act 1中的場景數(shù)量:
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(_ :)方法在每個字符串中的擴展字形集群之間執(zhí)行逐個字符的規(guī)范等價比較事期,如字符串和字符平等中所述。
字符串的Unicode表示形式
使用三種其他符合Unicode的表示之一訪問字符串值:
- 一組UTF-8代碼單元(使用字符串的utf8屬性訪問)
- 一組UTF-16代碼單元(使用字符串的utf16屬性訪問)
- 21位Unicode標量值的集合纸颜,等同于字符串的UTF-32編碼形式(使用字符串的unicodeScalars屬性訪問)