본문 바로가기
iOS Swift/문법

[Swift] String Comparison & Searching

by 야고이 2024. 2. 21.
728x90

240221_3

240315

String Comparison

연산자로 비교 하는 방법

let bigA = "Apple"
let smallA = "apple"
let b = "Banana"

bigA == smallA // false
bigA != smallA // true

bigA < smallA //true

//아스키코드
("A" as Character).asciiValue  //65
("a" as Character).asciiValue  //97

bigA < b //false

 

 

Method 로 비교 하는 방법

//순서가 같은지 비교
bigA.compare(smallA) == .orderedSame  //false (대소문자 구분함)
bigA.caseInsensitiveCompare(smallA) == .orderedSame // true 대소문자 구분하지 않고 비교
// 위랑 같은 코드
bigA.compare(smallA, options: [.caseInsensitive]) == .orderedSame // true

*caseInsensitive :  대소문자 무시

 

 

Finding Substrings

let str = "Hello, Swift"
str.contains("Swift") //문자열이 포함되어 있는지 확인. 결과 true
str.contains("swift") //소문자로 했을 때 false. 대소문자 구분하기 때문

str.lowercased().contains("swift") //대소문자 관계 없이 true


//범위 검색
str.range(of: "swift", options: [.caseInsensitive])
//Range(Swift.String.Index(_rawBits: 459015)..<Swift.String.Index(_rawBits: 786439))


//공통 접두어 검색
let str2 = "Hello, Programming"
let str3 = str2.lowercased()

var common = str.commonPrefix(with: str2)

//세번째 문자열과 비교
common = str.commonPrefix(with: str3) //첫번째 문자부터 다르기 때문에 공통된 접두어가 없다고 판단
common = str.commonPrefix(with: str3, options: [.caseInsensitive])
common = str3.commonPrefix(with: str, options: [.caseInsensitive]) //최종결과를 str3에서 가져옴

728x90

'iOS Swift > 문법' 카테고리의 다른 글

UITableViewDataSource, UITableViewDelegate  (1) 2024.02.28
[Swift] Array  (0) 2024.02.22
[Swift] String Editing #2  (0) 2024.02.21
[Swift] Optionals  (0) 2024.02.21
[Swift] String Editing #1  (0) 2024.02.21

댓글