replaceSubrange(_:with:)
https://developer.apple.com/documentation/swift/array/replacesubrange(_:with:)-6a2ai
replaceSubrange(_:with:) | Apple Developer Documentation
Replaces a range of elements with the elements in the specified collection.
developer.apple.com
- ✅ 파라미터의 개수 : 2개(_ subrange, with)
mutating func replaceSubrange<C>(
_ subrange: Range<Int>,
with newElements: C
) where Element == C.Element, C : Collection
🧑💻 _ subrange
- 교체할 배열의 범위를 뜻한다. 예를 들어 배열의 총 길이가 15일때 10까지만 교체하고 싶다면 10을 넣어주면 된다!
🧑💻 with(newElements)
- 배열에 교체(추가)할 새 요소를 뜻한다. 자세한 설명은 예제를 통해서!
var nums = [10, 20, 30, 40, 50]
nums.replaceSubrange(1...3, with: repeatElement(1, count: 5))
print(nums)
// Prints "[10, 1, 1, 1, 1, 1, 50]"
👉 초기 Int형 nums 배열에는 index 0부터 4까지 값이 들어있다.
이때, replaceSubrange(_ subrange, with)를 통해 nums 배열에 index 1부터 3까지, [1, 1, 1, 1, 1]로 추가한 것이다!
✅ 시간복잡도 O(n + m) , n은 배열의 길이, m은 집어넣을 새로운 요소의 길이를 뜻한다.
해당 함수를 배우게 된 문제
https://www.acmicpc.net/problem/10798
10798번: 세로읽기
총 다섯줄의 입력이 주어진다. 각 줄에는 최소 1개, 최대 15개의 글자들이 빈칸 없이 연속으로 주어진다. 주어지는 글자는 영어 대문자 ‘A’부터 ‘Z’, 영어 소문자 ‘a’부터 ‘z’, 숫자 ‘0’
www.acmicpc.net
🧑💻 replaceSubrange 사용해보기!
import Foundation
var arr = Array(repeating: Array(repeating: "", count: 15), count: 5)
for i in 0..<5{
let word = readLine()!.map{ String($0) }
let lastIndex = word.count - 1
arr[i].replaceSubrange(0..<lastIndex, with: word)
}
var result = ""
for i in 0..<15{
for j in 0..<5{
if arr[j][i] != ""{
result += arr[j][i]
}
}
}
print(result)
👉 답안을 보기 전에 실제로 사용해보고 풀어보자!
String형 이차원 배열은 ""로 초기화가 되어있고, 세로로 읽어야 하는데 기존에 readLine()!.map{ String($0) }를 배열에 집어넣으면 초기화가 되서 공백이 사라진다ㅠㅠㅠ 그래서 읽어들인 단어의 길이를 세어주고, 해당 단어의 길이까지만 word를 넣어 기존의 ""를 교체해주고 남은 부분은 ""을 유지시켜 IndexError를 피할 수 있었다!
'iOS > 문법' 카테고리의 다른 글
[Swift] Deque Struct(구조체)와 Class(클래스) 구현하기! (0) | 2023.10.05 |
---|---|
[Swift] Queue Struct(구조체)와 Class(클래스) 구현하기! (0) | 2023.10.03 |
[Swift] 특수 문자열 출력하기( \, ") (0) | 2023.09.23 |
[Swift] 문자열 쪼개기(components VS split) (0) | 2023.09.22 |
[Swift] 뒤집기 - reversed() / 자리 바꾸기 - swapAt(_:_:) (0) | 2023.09.22 |