哈哈哈件余,剛才看見微博,有人推薦一個神奇的工具,推薦給大家http://swiftlang.ng.bluemix.net/#/repl是IBM公司出的像吻,編譯器的版本是Swift2.2,現(xiàn)在可以使用之前的String的那些方法了,哈哈哈
插入和刪除(Inserting and Removing)
調(diào)用insert(_:atIndex:)方法可以在一個字符串的指定索引插入一個字符
var welcome = "hello"
welcome.insert("!",atIndex:welcome.endIndex)
//welcome現(xiàn)在就是"hello!"
還可以在一個字符串的指定索引插入一個字符串,調(diào)用insertContentsOf(_:at:)方法
welcome.insertContentsOf(" there".characters, at: welcome.endIndex.predecessor())
現(xiàn)在welcome就是"hello there!"(是接著上面的例子哦复隆,暫時的編譯器還是會報錯的拨匆,待升級之后再試試)
調(diào)用removeAtIndex(_:) 方法可以在一個字符串的指定索引刪除一個字符
var welcome = "hello there!"
welcome.removeAtIndex(welcome.endIndex.predecessor())
//這時候welcome的值就是"hello there",把最后一個字符后一位的前一位移除了就是移除了"!"
調(diào)用removeRange(_:)方法可以在一個字符串指定索引刪除一個子字符串
var welcome = "hello there"
let range = welcome.endIndex.advanceBy(-6)..<welcome.endIndex
welcome.removeRange(range)
DAY2里面說過挽拂,我們可以調(diào)用advanceBy()來獲取一個索引惭每,編譯器的原因暫時不能實現(xiàn),上面的例子表示的意思是從空格刪除到最后的e,welcome現(xiàn)在就等于hello
比較字符串(Comparing Strings)
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 string are considered equal")
}
//These two string are considered equal
我們可以使用(==)和(!=)來比較台腥,如果兩個字符串的可擴展的字形群集是標準相等的宏赘,那么它們就是相等的,即使可擴展的字形群集是由不同的Unicode標量構(gòu)成的黎侈,只要語言意義和外觀相同就認為是相同的.
let a = "caf\u{E9}" //é
let b = "caf\u{65}\u{301}" //e和重音符號
if a == b{
print("These two strings are considered equal")
}
//These two strings are considered equal
前綴/后綴相等(Prefix and Suffix Equality )
通過調(diào)用字符串hasPrefix()/hasSuffix()方法來檢查是否有前后綴察署,兩個都輸入一個String類型的參數(shù),返回一個布爾值峻汉。這里舉了一個例子贴汪,用一個定義為常量的數(shù)組romeoAndJuliet,可以看見休吠,數(shù)組是用[]來申明的扳埂,數(shù)組內(nèi)的變量用逗號隔開,具體的數(shù)據(jù)類型我看后面有詳細的章節(jié)會講瘤礁,到時候?qū)W習
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"
]
定義了一個變量用來計數(shù)前綴中含有Act 1的阳懂,這里一共有五次
var act1SceneCount = 0
for scene in romeoAndJuliet {
if scene.hasPrefix("Act 1"){
++act1SceneCount
}
}
print("There are \(act1SceneCount) scenes in Act 1")
//There are 5 scenes in Act 1
定義了兩個變量,來數(shù)字符串后綴中含有這兩個的值,這里有一個for循環(huán)一個if柜思,else if循環(huán)岩调,具體的語法后面也有詳細的章節(jié)講解
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
}
}
print("\(mansionCount) mansion scenes;\(cellCount) cell scenes")
//6 mansion scenes;2 cell scenes
Unicode Representations of Strings
apple的String&Character中還有這個章節(jié)Unicode Representations of Strings,這里就不示范了酝蜒,有興趣的大家可以看一下誊辉,我睡覺前看下~