Swift提供了3种方式去比较文本值:比较字符串和字符相等,比较前缀相等,比较后缀相等。
比较字符串和字符相等
比较字符串和字符相等可以使用相等运算符(==)和不相等运算符(!=):
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")
}
// 打印 "These two strings are considered equal
2个字符串或者2个字符,如果它们的字形集是按照一定规则相等的,就可以认为它们是相等的。字形集是按照一定规则相等是指它们有一样的语言意义和外观,即使它们其实由不同的Unicode标量组成。
比如标量LATIN SMALL LETTER E WITH ACUTE (U+00E9)和LATIN SMALL LETTER E (U+0065)加上COMBINING ACUTE ACCENT (U+0301)就可以被认为是一定定义上相等的。它们的字形集都可以表示字符é,所以它们被认为是一定规则上的相等。如下:
// LATIN SMALL LETTER E WITH ACUTE
let eAcuteQuestion = "Voulez-vous un caf\u{E9}?" // Voulez-vous un café?
// using LATIN SMALL LETTER E and COMBINING ACUTE ACCENT
let combinedEAcuteQuestion = "Voulez-vous un caf\u{65}\u{301}?" //Voulez-vous un café?
if eAcuteQuestion == combinedEAcuteQuestion {
print("These two strings are considered equal")
}
// 打印 "These two strings are considered equal”
相反的,英语国家使用的LATIN CAPITAL LETTER A (U+0041, or "A")和俄语国家使用的CYRILLIC CAPITAL LETTER A (U+0410, or "А")就被认为是不相等的。这2个字符看起来很像,但是它们的语意是不一样的:
let latinCapitalLetterA: Character = "\u{41}"
let cyrillicCapitalLetterA: Character = "\u{0410}"
if latinCapitalLetterA != cyrillicCapitalLetterA {
print("These two characters are not equivalent.")
}
// 打印 "These two characters are not equivalent.”
NOTE:Swift中的字符串和子符的比较不是地点敏感的。
前缀相等和后缀相等
判断字符串是不是有特定的前缀或者后缀,可以使用方法hasPrefix(_:)和hasSuffix(_:)。2个方法的入参都是一个字符串,然后返回布尔值。
下面的例子中是一个包含了字符串的数组,里面是莎士比亚的罗密欧和朱丽叶的前两个场景:
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(_:)计算出数组romeoAndJuliet中第一个场景的数量:
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(_:)计算出发生在Capulet’s mansion和Friar Lawrence’s cel的场景:
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")
// Prints "6 mansion scenes; 2 cell scenes”
NOTE:方法hasPrefix(_:)和hasSuffix(_:)对每一个字符串的字形集按照上面提的一定规则得相等进行逐字比较。
网友评论