发布于 2015-06-14 01:51:23 | 298 次阅读 | 评论: 0 | 来源: 网络整理

比较字符串 (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”
最新网友评论  共有(0)条评论 发布评论 返回顶部

Copyright © 2007-2017 PHPERZ.COM All Rights Reserved   冀ICP备14009818号  版权声明  广告服务