Geon

신규 아이디 추천 본문

코딩테스트

신규 아이디 추천

jgkim1008 2022. 3. 15. 21:59

해결코드

 

func solution(_ new_id:String) -> String {
    //1단계
    let input = new_id.lowercased()

    // 2단계
    var result = ""

    for i in input {
        if i.isLetter || i.isNumber || i == "-" || i == "_" || i == "." {
            result += String(i)
        }
    }

    // 3단계
    while result.contains("..") {
            result = result.replacingOccurrences(of: "..", with: ".")
    }


    //4단계

    while result.hasPrefix(".") {
        result.removeFirst()
    }

    while result.hasSuffix(".") {
        result.removeLast()
    }

    //5단계
    if result.isEmpty {
        result = "a"
    }

    // 6단계
    if result.count >= 16 {
        let index = result.index(result.startIndex, offsetBy: 15)
        result = String(result[result.startIndex..<index])
        if result.hasSuffix(".") {
            result.removeLast()
        }
    }

    // 7단계
    if result.count <= 2  {
        while result.count < 3 {
            result += String(result.last!)
        } 
    }
    return result
}

 

배운점

  • .isLetter, isNumber 로 숫자냐 문자열이냐를 판별할수 있다.
  • index(_,offsetBy:) 로 원하는 문자열 길이를 잘라낼수 있다.

'코딩테스트' 카테고리의 다른 글

단어뒤집기[BOJ]  (0) 2022.03.22
스택[BOJ]  (0) 2022.03.22
신고 결과 받기  (0) 2022.03.18
로또의 최고 순위와 최저 순위  (0) 2022.03.16
숫자 문자열과 영단어  (0) 2022.03.15