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")
}
// Prints "These two strings are considered equal"
2개의 String 값 또는 2개의 Character 값은 확장된 문자소 클러스터가 정규적으로 동일한 경우 2개의 값이 같다고 한다.
확장된 문자소 클러스터는 다른 유니코드 스칼라로 구성되어 있더라도 언어적 의미와 모양이 같으면 정규적으로 같다고 한다.
예를 들어 LATIN SMALL LETTER E WITH ACUTE (U+00E9)과 LATIN SMALL LETTER E (U+0065) 뒤에 COMBINING ACUTE ACCENT (U+0301)가 오는 것은 정규적으로 같다.
이러한 확장된 문자소 클러스터는 문자 é 을 표시하는 유효한 방법이므로 동일하다고 간주한다.
// "Voulez-vous un café?" using 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}?"
if eAcuteQuestion == combinedEAcuteQuestion {
print("These two strings are considered equal")
}
// Prints "These two strings are considered equal"
반대로 영어로 사용된 LATIN CAPITAL LETTER A (U+0041, or "A")와 러시아어로 사용된 CYRILLIC CAPITAL LETTER A (U+0410, or "А")은 같지 않다.
이 문자들은 모양은 같지만 언어적 의미가 같지 않기 때문이다.
let latinCapitalLetterA: Character = "\u{41}"
let cyrillicCapitalLetterA: Character = "\u{0410}"
if latinCapitalLetterA != cyrillicCapitalLetterA {
print("These two characters are not equivalent.")
}
// Prints "These two characters are not equivalent."
문자열이 특정 문자열 접두사 또는 접미사를 가지고 있는지 확인하기 위해 문자열의 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(_:) 메소드를 이용하여 remeoAndJuliet 배열의 연극 Act 1의 장면 개수를 카운트할 수 있다.
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"
마찬가지로 hasSuffix(_:) 메서드를 사용하여 Capulet’s mansion 과 Friar Lawrence’s cell 의 장면의 개수를 구할 수 있다.
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(:) 메서드는 문자열과 문자 같음 (String and Character Equality) 에서 설명했듯이 각 문자열에 확장된 문자소 클러스터 간의 문자 단위로 동등한지를 수행한다.