通过调用字符串的 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" ]
你可以调用 hasPrefix(_:)
方法来计算话剧中第一幕的场景数:
var act1SceneCount = 0 for scene in romeoAndJuliet { if scene.hasPrefix("Act 1 ") { act1SceneCount += 1 } } print("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 += 1 } else if scene.hasSuffix("Friar Lawrence's cell") { cellCount += 1 } } print("\(mansionCount) mansion scenes; \(cellCount) cell scenes") // 打印输出“6 mansion scenes; 2 cell scenes”
注意
hasPrefix(_:)
和hasSuffix(_:)
方法都是在每个字符串中逐字符比较其可扩展的字符群集是否标准相等,详细描述在 字符串/字符相等。