[프로그래머스] 신규 아이디 추천 - Swift

이창형·2023년 5월 12일
0

https://school.programmers.co.kr/learn/courses/30/lessons/72410
문제 링크

코드

import Foundation

func solution(_ new_id:String) -> String {
    var new_id = new_id
    new_id = new_id.lowercased()
    new_id = new_id.filter{$0.isLetter || $0 == "-" || $0 == "_" || $0 == "." || $0.isNumber}
    while new_id.contains("..") {
        if !new_id.contains("..") {
            break
        }
        new_id = new_id.replacingOccurrences(of: "..", with: ".")
    }
    if Array(new_id)[0] == "." {
        new_id.removeFirst()
    }
    if Array(new_id).last == "." {
        new_id.removeLast()
    }
    if new_id.isEmpty {
        return "aaa"
    }
    while new_id.count > 15 {
        new_id.removeLast()
    }
    if new_id.last == "." {
        new_id.removeLast()
    }
    while new_id.count <= 2 {
        new_id.append(new_id.last!)
    }

    return new_id
}

회고

  • 문자열 처리만 잘 할 수 있으면 문제 그대로 코딩을 하면 된다
  • replacingOccurrences(of:, with:)을 알게 되었다
  • of를 with로 바꿔주는 것 !! 외우자
profile
iOS Developer

0개의 댓글