位置:首頁 > 高級語言 > Swift教學 > Swift比較字符串

Swift比較字符串

比較字符串 (Comparing Strings)

Swift 提供了三種方式來比較字符串的值:字符串相等、前綴相等和後綴相等。

字符串相等 (String Equality)

如果兩個字符串以同一順序包含完全相同的字符,則認為兩者字符串相等:

let quotation = "我們是一樣一樣滴."
let sameQuotation = "我們是一樣一樣滴."
if quotation == sameQuotation {
    println("這兩個字符串被認為是相同的")
}
// 打印輸出:"這兩個字符串被認為是相同的"

前綴/後綴相等 (Prefix and Suffix Equality)

通過調用字符串的hasPrefix/hasSuffix方法來檢查字符串是否擁有特定前綴/後綴。 兩個方法均需要以字符串作為參數傳入並傳出Boolean值。 兩個方法均執行基本字符串和前綴/後綴字符串之間逐個字符的比較操作。

下麵的例子以一個字符串數組表示莎士比亞話劇《羅密歐與朱麗葉》中前兩場的場景位置:

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方法來計算話劇中第一幕的場景數:

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方法來計算發生在不同地方的場景數:

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”