[SWIFT]문자열 섞기

힐링힐링·2023년 9월 20일
0

알고리즘

목록 보기
5/7

문제

str1.index(str1.startIndex,offsetBy:) 로 인덱스의 위치를 구한다음
str1[]에 넣어서 구했다.

import Foundation

func solution(_ str1:String, _ str2:String) -> String {
    
    var cnt : Int = str1.count 
    var result : String = ""
    //특정 index문자 구하기.. 
    // str1[시작지점부터 번째 떨어진 index]
    for i in 1...cnt{
    
        result += String(str1[str1.index(str1.startIndex, offsetBy: i-1)])
        result += String(str2[str2.index(str2.startIndex, offsetBy: i-1)])
    }
    return result

}

더 좋은답

zip을 만든다음 map하여 joined한다.

import Foundation

func solution(_ str1:String, _ str2:String) -> String {
    return zip(str1, str2).map { String($0) + String($1) }.joined()
}
profile
블로그 이전합니다 https://james-kim-tech.tistory.com/

0개의 댓글

Powered by GraphCDN, the GraphQL CDN