스파르타 코딩 클럽 - iOS 스타터 6기/알고리즘 코드카타

23. 스파르타 코딩 클럽 - 4월 23일 코딩테스트 연습 (코드카타)

seongpil Heo 2025. 4. 23. 20:49

❓ 오늘의 문제

1. 잘라서 배열로 저장하기

  • 문자열 my_str과 n이 매개변수로 주어질 때, my_str을 길이 n씩 잘라서 저장한 배열을 return하도록 solution 함수를 완성해 주세요.

나의 정답 코드

import Foundation

func solution(_ my_str:String, _ n:Int) -> [String] {
    var result = [String]()
    var i = 0
    while i < my_str.count {
        let startIndex = my_str.index(my_str.startIndex, offsetBy: i)
        let endIndex = my_str.index(startIndex, offsetBy: n, limitedBy: my_str.endIndex) ?? my_str.endIndex
        let substring = String(my_str[startIndex..<endIndex])
        result.append(substring)
        i += n
    }
    return result
}

 ✓ TIL

오랜만에 알고리즘 문제를 풀었다...

오늘의 문제는 잘라서 배열로 저장하기이다.

 

배열이 주어지고 int 값 n 이 주어질 때

배열을 n씩 잘라서 저장하고 출력하는 문제이다.

 

나는 이 문제를 해결하기 위해서 my_str[0:5] 처럼 시작점부터 끝점까지 result 배열 변수에 따로 저장하는 식으로

문제를 해결하려고 했지만 스위프트에서는 my_str[0:5] 같은 문법이 불가능하기 때문에 다른 방법을 찾아보았다.

 

my_str[0:5] 대신 my_str[0..<5]는 가능하기 때문에

처음 인덱스와 끝 인덱스를 변수로 선언하고 두개의 변수를 사용하여 배열을 자르고 저장하였다.

 

// 시작 인덱스
let startIndex = my_str.index(my_str.startIndex, offsetBy: i)

// 끝 인덱스
let endIndex = my_str.index(startIndex, offsetBy: n, limitedBy: my_str.endIndex) ?? my_str.endIndex

 

 

myStr.index(myStr.startIndex, offsetBy: i) 는 현재 i번 문자 인덱스를 구하는 것이고,

 

myStr.index(startIndex, offsetBy: n, limitedBy: myStr.endIndex) 는 끝나는 인덱스를 구하는데 문자열 끝을 넘지 않도록 제한한다.

 

while i < my_str.count {

}

 

 

문자열 길이만큼 while문을 반복하며

 

let substring = String(my_str[startIndex..<endIndex])
result.append(substring)

 

구한 인덱스 범위로 부분 문자열 슬라이싱을 한다.

 

그 후 출력할 result 변수에 append 한다.

 

i += n

 

그리고 주어진 n만큼 자르는 것이므로

i의 값에 n을 더해준다.


 😼 GitHub