Focus On Develop ๐ŸคŸ๐ŸคŸ

[Swift] String.Index ๋ณธ๋ฌธ

iOS [Swift]/๊ธฐ์ดˆ๋ฅผ ํƒ„ํƒ„ํžˆ!

[Swift] String.Index

๋ˆ„๋ฆฌ๋‹ฌ์ดํ‹€ 2020. 12. 17. 11:09

์ƒ์„ธ ์ •๋ณด : String.Index | Apple Document 

 

 

๋‹ค๋ฅธ ์–ธ์–ด๋“ค(C, JAVA, Python ๋“ฑ)์€ String์ด ์ฃผ์–ด์กŒ์„๋•Œ, ๋ฐ”๋กœ Character์˜ ๋ฐฐ์—ด์ฒ˜๋Ÿผ ์ธ๋ฑ์Šค๋กœ ์ ‘๊ทผ์ด ๊ฐ€๋Šฅํ•˜๋‹ค.

๊ทธ๋Ÿฐ๋ฐ.. Swift์˜ String์€ Index(์ˆซ์ž) ๋กœ ํŠน์ • ๋ฌธ์ž๋กœ ์ ‘๊ทผ์ด ๋ถˆ๊ฐ€๋Šฅํ•˜๊ธฐ ๋•Œ๋ฌธ์—, ํŠน์ • ๋ฌธ์ž๋กœ ๋ฐ”๋กœ ์ ‘๊ทผํ•˜๊ธฐ ์œ„ํ•ด์„œ๋Š” String.Index Type๋ฅผ ์‚ฌ์šฉํ•ด์•ผํ•œ๋‹ค.

 

๋ช‡๊ฐ€์ง€ ์˜ˆ์‹œ๋ฅผ ๋ณด๋ฉด์„œ ์ž์„ธํžˆ ์‚ดํŽด๋ณด์ž.

let string = "hello"
let firstCharacter = string[0] // ERROR

์ด๋ ‡๊ฒŒ String์— ์ˆซ์ž Index๋กœ ๋ฐ”๋กœ ์ ‘๊ทผ์„ ๋ชปํ•œ๋‹ค.

 

๋Œ€์‹ ์— String.Index Type์œผ๋กœ startIndex(์‹œ์ž‘), endIndex(๋)์„ ๊ฐ€๋ฆฌํ‚ค๋Š” Index๋ฅผ ์ œ๊ณตํ•ด์ค€๋‹ค. ๊ทผ๋ฐ ์—ฌ๊ธฐ์„œ ์ฃผ์˜ํ•ด์•ผ ํ• ์ ์€ startIndex๋Š” ์šฐ๋ฆฌ๊ฐ€ ์ƒ์‹์ ์œผ๋กœ ์ƒ๊ฐํ•˜๋Š” ์ฒซ๋ฒˆ์งธ ๋ฌธ์ž, 0๋ฒˆ ์ธ๋ฑ์Šค๋ฅผ ๊ฐ€๋ฅดํ‚ค๋Š”๋ฐ, endIndex๋Š” ์ •๋ง String์˜ ๋งˆ์ง€๋ง‰ ๋ฌธ์ž (ํ”ํžˆ ๋งํ•˜๋Š” '\0')๋ฅผ ๊ฐ€๋ฅดํ‚จ๋‹ค.

๊ทธ๋ž˜์„œ ์นœ์ ˆํ•˜๊ฒŒ๋„ String.Index(after / before) ๊ธฐ๋Šฅ์„ ์ œ๊ณตํ•œ๋‹ค.

let firstIndex = string[string.startIndex] // 'h'
string[string.endIndex] // Out Of Range Crash
string[string.Index(after: firstIndex)] // 'e'
string[string.Index(before: string.endIndex)] // 'o'

 

์•„๋ฌด๋ฆฌ ๊ทธ๋ž˜๋„ ์•„์ง์€ ์šฐ๋ฆฌ์˜ ์„ฑ์— ์ฐจ์ง€ ์•Š๋Š”๋‹ค. ์‘..? ๊ทธ๋Ÿผ ์ค‘๊ฐ„์— ์žˆ๋Š” ํŠน์ • ๋ฌธ์ž๋ฅผ ์ฐพ์œผ๋ ค๋ฉด after, after, ํ•˜๋ฉด์„œ ์ฐพ์•„์•ผ๋˜์š”?? ใ… ใ…  ์•„๋‹ˆ์š”!! ๋‹คํ–‰ํžˆ๋„ offset์„ ์ด์šฉํ•ด์„œ ์ ‘๊ทผํ•˜๋Š” ๊ฒƒ๋„ ์ œ๊ณตํ•œ๋‹ค. ๋ฌผ๋ก  ํŠน์ • ๋ฌธ์ž๊ฐ€ ์–ด๋”” ์žˆ๋Š”์ง€ Index๋ฅผ ์ฐพ๋Š”๊ฒƒ๋„ ๊ฐ€๋Šฅ!

let randomIndex = string.index(string.startIndex, offsetBy: 2) 
string[randomIndex] // 'l'
string.index(of: "e") // 2

 

๊ทธ๋ฆฌ๊ณ .. ์•„์‰ฝ๊ฒŒ๋„ Swfit์—์„œ .substring์„ ๋ฐ”๋กœ ์‚ฌ์šฉํ•˜๋„๋ก ์ œ๊ณตํ•˜์ง€๋Š” ์•Š๋Š”๋‹ค ใ… .ใ…  ๋Œ€์‹  String.Index๋ฅผ ํ™œ์šฉํ•ด์„œ ์ˆ˜๋™(?)์œผ๋กœ ๊ตฌํ˜„์€ ๊ฐ€๋Šฅํ•˜๋‹ค! ๐Ÿ˜‚ ๐Ÿ˜‚ ์‘..?? hell?? ใ…‹ใ…‹ใ…‹ใ…‹ Swift์—์„œ String์„ ์„ธ๋ฐ€ํ•˜๊ฒŒ ๋‹ค๋ฃจ๋Š”๊ฑด ํ—ฌ์ด๋ผ๊ตฌ..?? ์ธ์ •.. ๐Ÿ‘Š๐Ÿ‘Š

let startIndex = string.startIndex
let endIndex = string.index(string.endIndex, offsetBy: -2) // offset์— ์Œ์ˆ˜๋„ ๊ฐ€๋Šฅํ•˜๋‹ต๋‹ˆ๋‹ค!
let substring = string[startIndex...endIndex]  // "hell"

 

๋†๋‹ด์ด๊ณ .. substring๋„ String extension์œผ๋กœ ํ•œ๋ฒˆ๋งŒ ๊ตฌํ˜„ํ•ด๋†“์œผ๋ฉด, ์˜คํžˆ๋ ค ๋‹ค๋ฅธ ์–ธ์–ด๋“ค๋ณด๋‹ค ๋” ์›ํ•˜๋Š” ๊ธฐ๋Šฅ์— ๋งž์ถ˜? ๊ตฌํ˜„๋„ ๊ฐ€๋Šฅํ•  ๊ฒƒ ๊ฐ™๋‹ค!

 

PS. ์•„๋ž˜์ฒ˜๋Ÿผ String ํƒ€์ž…์„ Array๋กœ Castingํ•ด๋ฒ„๋ฆฌ๋ฉด, array[index]์™€ ๊ฐ™์ด ์ธ๋ฑ์Šค๋กœ ์ ‘๊ทผ์ด ๊ฐ€๋Šฅํ•˜๋‹ค.. ๐Ÿ˜‚

let array = Array(string)

'iOS [Swift] > ๊ธฐ์ดˆ๋ฅผ ํƒ„ํƒ„ํžˆ!' ์นดํ…Œ๊ณ ๋ฆฌ์˜ ๋‹ค๋ฅธ ๊ธ€

[Swift] Core Data(1) ๊ฐœ๋…์ •๋ฆฌ  (0) 2020.12.21
[Swift] String.components  (0) 2020.12.18
[Swift] String Radix๋ฅผ ํ†ตํ•œ ์ง„๋ฒ•๋ณ€ํ™˜  (0) 2020.12.16
[Swift] enumerated()  (0) 2020.12.16
[Swift] Set  (0) 2020.12.15
Comments