본문 바로가기

코딩코오딩

[Swift] String - #5 Comparing Strings


문자열 비교

String은 '==', '!=' operator를 사용해서 비교한다.

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")
}
// Prints "These two strings are considered equal"

 

확장 문자소 클러스터에 의해서 실제 다른 유니코드 스칼라의 조합이더라도 언어적인 의미와 모양이 같은 경우에 동일하다고 판단한다.

래 그림과 같이 \u{E9}나  \u{65}\u{301}는 모두 é를 나타내는 확장 문자소 클러스터이기 때문에 두 문자열의 비교는 true를 리턴한다. 

반대로 영어의 LATIN CAPITAL LETTER A (U+0041, or "A")와 러시아어의 CYRILLIC CAPITAL LETTER A (U+0410, or "А")는 다른 언어이기 때문에 외형은 비슷하지만 다른 문자로 처리된다.

String의 특정한 prefix나 suffix를 갖는지 체크하기 위해서 hasPrefix(_:)hasSuffix(_:)를 메소드를 사용한다. 여기서도 확장 문자소 클러스터간의 문자열 비교를 수행한다.

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"
]

var act1SceneCount = 0
for scene in romeoAndJuliet {
    if scene.hasPrefix("Act 1 ") {
        act1SceneCount += 1
    }
}
print("There are \(act1SceneCount) scenes in Act 1")
// Prints "There are 5 scenes in Act 1"

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"