본문 바로가기
Swift

[Swift] split vs components

by thoonk: 2021. 6. 5.

String을 분리하는 함수 split과 components의 차이에 관해 기록합니다.

 

split

func split(separator: Character, 
	maxSplits: Int = Int.max, 
	omittingEmptySubsequences: Bool = true) -> [Substring]

separator: 문자열을 분리하려는 문자 기준 

maxSplits: 문자열을 분리하는 횟수

omittingEmptySubsequences: 빈 시퀀스의 포함 유무

return type: [Substring]

time Complextiy: O(n), n은 Collection의 길이

 

예제:

let str = "Hello Swift"
let arr = str.split(separator: " ") // ["Hello", "Swift"]

let str = "Hello Swift How are you?" 
let arr = str.split(separator: " ", maxSplits: 1) // ["Hello", "Swift How are you?"]

let str = "Hello, ,Swift"
let arr = str.split(separator: ",", omittingEmptySubsequences: false) // ["Hello", " ", "Swift"]

components

func components(separatedBy separator: CharacterSet) -> [String]

separator: 문자열을 분리하려는 문자 기준

이 메서드는 사용하려면 Foundation 프레임워크를 import해야 한다.

retrun type: [String]

 

예제: 

import Foundation

let str = "Hello Swift How are you?"
let arr = str.components(separatedBy: " ")
// ["Hello", "Swift", "How", "are", "you?"]

 

split에 더 손이 가긴 하지만 용도에 맞게 사용하면 될거 같습니다🙃

부족한 점 피드백해주시면 감사합니다!

 

 

참고:

https://developer.apple.com/documentation/swift/string/2894564-split

https://developer.apple.com/documentation/foundation/nsstring/1410120-components

'Swift' 카테고리의 다른 글

[Swift] Equatable, Hashable  (0) 2023.01.03
[Swift] @discardableResult  (2) 2021.07.18
[Swift] Optional  (0) 2021.05.22
[Swift] ARC (1)  (0) 2021.05.12
[Swift] popLast() vs removeLast()  (0) 2021.05.11

댓글