์ƒ์„ธ ์ปจํ…์ธ 

๋ณธ๋ฌธ ์ œ๋ชฉ

components์™€ split ๋ฉ”์„œ๋“œ ๋น„๊ต / ๋ฌธ์ž์—ด์„ ํŠน์ • ๋ฌธ์ž๋ฅผ ๊ธฐ์ค€์œผ๋กœ ๋ฐฐ์—ด๋กœ ๋ณ€ํ™˜

๐ŸŽ iOS/Swift

by AHN.Jihyeon 2024. 6. 27. 01:44

๋ณธ๋ฌธ

 

์ฝ”๋”ฉํ…Œ์ŠคํŠธ ๋ฌธ์ œ๋ฅผ ํ’€๋‹ค ๋ณด๋ฉด ์ž์ฃผ ์‚ฌ์šฉํ•˜๋Š” ๋ฉ”์„œ๋“œ๋“ค์ด์ง€๋งŒ

๋น„์Šทํ•œ ๊ธฐ๋Šฅ ๋•Œ๋ฌธ์ธ์ง€ ๋งค๋ฒˆ ํ—ท๊ฐˆ๋ฆฌ๊ณค ํ•œ๋‹ค. 

์ด์ฐธ์— ์ œ๋Œ€๋กœ ์ •๋ฆฌ๋ฅผ ํ•ด๋ณด๊ณ ์ž ํ•œ๋‹ค. 

 

 


๊ณตํ†ต์ 

components(separatedBy:) ๋ฉ”์„œ๋“œ์™€ split ๋ฉ”์„œ๋“œ๋Š” 

๋ฌธ์ž์—ด์„ ํŠน์ • ๊ตฌ๋ถ„์ž๋ฅผ ๊ธฐ์ค€์œผ๋กœ ๋ถ„๋ฆฌํ•˜์—ฌ ๋ฐฐ์—ด๋กœ ๋ฐ˜ํ™˜ํ•œ๋‹ค. 

 

 

 

 

components(separatedBy:) 

Swift์˜ String ํƒ€์ž…์— ์ •์˜๋œ ๋ฉ”์„œ๋“œ

 

  • ๊ตฌ๋ถ„์ž ํƒ€์ž…: ๋‹จ์ผ ๋ฌธ์ž, ๋ฌธ์ž์—ด(String) ๋˜๋Š” ๋ฌธ์ž์—ด ๋ฐฐ์—ด([String])
let text = "one,two;three four"

let componentsResult = text.components(separatedBy: [",", ";", " "])
print(componentsResult) // ["one", "two", "three", "four"]

 

 

  • ๋ฐ˜ํ™˜ ํƒ€์ž…: ๋ฌธ์ž์—ด ๋ฐฐ์—ด([String])
let text = "apple,banana,orange"
let fruits = text.components(separatedBy: ",") // [String] ํƒ€์ž…
print(fruits) //์ถœ๋ ฅ: ["apple", "banana", "orange"]

 

 

  • ๋นˆ ๋ฌธ์ž์—ด ์ฒ˜๋ฆฌ : ๊ตฌ๋ถ„์ž๊ฐ€ ์—ฐ์†์œผ๋กœ ์žˆ์„ ๋•Œ ๋นˆ ๋ฌธ์ž์—ด์„ ํฌํ•จ
let text = "one,,two"
let parts = text.components(separatedBy: ",")
print(parts) // ["one", "", "two"]

 

 

 


split(separator: )

  • ๊ตฌ๋ถ„์ž ํƒ€์ž…: ๋ฌธ์ž(Character)
  • ๋ฐ˜ํ™˜ ํƒ€์ž…: ์„œ๋ธŒ์ŠคํŠธ๋ง ๋ฐฐ์—ด([Substring])
    Substring์€ ์›๋ž˜ ๋ฌธ์ž์—ด์˜ ์ผ๋ถ€๋ฅผ ์ฐธ์กฐํ•˜๋ฏ€๋กœ ๋ฉ”๋ชจ๋ฆฌ ์‚ฌ์šฉ ์ธก๋ฉด์—์„œ ๋” ํšจ์œจ์ ์ผ ์ˆ˜ ์žˆ์Œ
    ํ•˜์ง€๋งŒ, Substring์„ ์žฅ๊ธฐ์ ์œผ๋กœ ์ €์žฅํ•˜๊ฑฐ๋‚˜ ๋‹ค๋ฅธ ๊ณณ์œผ๋กœ ์ „์†กํ•˜๋ ค๋ฉด String์œผ๋กœ ๋ณ€ํ™˜ํ•ด์•ผ ํ•œ๋‹ค. 
let text = "one,two,three"
let parts = text.split(separator: ",")
print(parts) // ["one", "two", "three"]

for part in parts {
    print(part) // ๊ฐ๊ฐ์˜ ์š”์†Œ๋Š” Substring
}

// Substring์„ String์œผ๋กœ ๋ณ€ํ™˜
let strParts = parts.map { String($0) }
print(strParts) // ["one", "two", "three"]

 

 

 

  • ๋นˆ ๋ฌธ์ž์—ด ์ฒ˜๋ฆฌ : omittingEmptySubsequences ์˜ต์…˜์„ ํ†ตํ•ด ๋นˆ ๋ฌธ์ž์—ด ์ƒ๋žต ๊ฐ€๋Šฅ 
    • omittingEmptySubsequences: ๋นˆ ๊ฒฐ๊ณผ๋ฅผ ์ƒ๋žตํ• ์ง€ ์—ฌ๋ถ€ (true๊ฐ€ ๊ธฐ๋ณธ๊ฐ’)
    • maxSplits: ์ตœ๋Œ€ ๋ถ„ํ•  ํšŸ์ˆ˜ (Int.max๊ฐ€ ๊ธฐ๋ณธ๊ฐ’)
let text = "one,,two"
let parts = text.split(separator: ",", omittingEmptySubsequences: false)
print(parts) // ["one", "", "two"]

let partsEmpty = text.split(separator: ",", omittingEmptySubsequences: true)
print(partsEmpty) // ["one", "two"]

 

 


๊ฒฐ๋ก 

  • ๊ฐ„๋‹จํ•œ ๊ตฌ๋ถ„์ž: split์ด ๋” ๊ฐ„๋‹จํ•˜๊ณ  ํšจ์œจ์ 
  • ์—ฌ๋Ÿฌ ๊ตฌ๋ถ„์ž ๋˜๋Š” ๋ฌธ์ž์—ด ๊ตฌ๋ถ„์ž: components(separatedBy:)๊ฐ€ ์ ํ•ฉ
  • ๋นˆ ๋ฌธ์ž์—ด ์ƒ๋žต: split์€ omittingEmptySubsequences ์˜ต์…˜์„ ์ œ๊ณตํ•ด ์„ธ๋ฐ€ํ•œ ์ œ์–ด๊ฐ€ ๊ฐ€๋Šฅ

 

๊ด€๋ จ๊ธ€ ๋”๋ณด๊ธฐ