본문 바로가기

프로그래머스 (Swift)/기초

[Day2-5] 문자열 겹쳐쓰기

문제

 

 

내 정답 코드

import Foundation

func solution(_ my_string:String, _ overwrite_string:String, _ s:Int) -> String {
    
    let index = my_string.index(my_string.startIndex, offsetBy: s)
    
    var resultString = String(my_string.prefix(upTo: index))
    resultString += overwrite_string
    resultString += String(my_string.suffix(from: my_string.index(index, offsetBy: overwrite_string.count)))
    
    return resultString
}

 

#

1. my_string에서 offsetBy만큼 떨어진 문자의 인덱스를 가져와 string.index 형태로 저장한다.

2. prefix를 이용하여 index값의 전 문자까지 잘라와 저장한다.

3. overwrite_string값을 붙여 저장한다.

4. suffix를 이용하여 나머지 붙여야 하는 문자들을 가져와서 추가 저장한다.

 

prefix, suffix가 없어도 string.index를 활용하여 일반 배열처럼 사용하여 해결해도 된다.

import Foundation

func solution(_ my_string:String, _ overwrite_string:String, _ s:Int) -> String {
    
    let startIndex = my_string.startIndex
    let endIndex = my_string.endIndex
    
    let overStartIndex = my_string.index(startIndex, offsetBy: s)
    let overEndIndex = my_string.index(overStartIndex, offsetBy: overwrite_string.count)
    
    // subString -> String 형변환이 필요
    let result = String(my_string[startIndex..<overStartIndex]) + overwrite_string + String(my_string[overEndIndex..<endIndex])
    
    return result
}

배운 기술

 

1. string.index
https://developer.apple.com/documentation/swift/string/index

 

String.Index | Apple Developer Documentation

A position of a character or code unit in a string.

developer.apple.com

 

2. string.index( )

https://developer.apple.com/documentation/swift/string/index(_:offsetby:)

 

index(_:offsetBy:) | Apple Developer Documentation

Returns an index that is the specified distance from the given index.

developer.apple.com

 

3. prefix(upto)

https://developer.apple.com/documentation/swift/string/prefix(upto:)

 

prefix(upTo:) | Apple Developer Documentation

Returns a subsequence from the start of the collection up to, but not including, the specified position.

developer.apple.com

 

3. suffix(from)

https://developer.apple.com/documentation/swift/array/suffix(from:)

 

suffix(from:) | Apple Developer Documentation

Returns a subsequence from the specified position to the end of the collection.

developer.apple.com