[Swift 알고리즘] 신규 아이디 추천

https://programmers.co.kr/learn/courses/30/lessons/72410

import Foundation


func solution(_ new_id:String) -> String {
    var myID = new_id
    
    //1
    myID = myID.lowercased()
    
    
    //2
    var newID = ""
    
    for i in myID {
        if i.isLetter || i.isNumber || i == "-" || i == "_" || i == "." {
            newID.append(i)
        }
    }
    
    //3
    if newID.contains("..") {
        
        while newID.contains("..") {
            newID = newID.replacingOccurrences(of: "..", with: ".")
        }
        
    }
    
    //4
    if newID.hasPrefix(".") {
        newID.removeFirst()
    }
    
    if newID.hasSuffix(".") {
        newID.removeLast()
    }
    
    
    //5
    if newID.isEmpty {
        newID = "a"
    }
    
    //6
    if newID.count >= 16 {
        let index = newID.index(newID.startIndex, offsetBy: 15)
        newID = String(newID[newID.startIndex..<index])
        
        if newID.hasSuffix(".") {
            newID.removeLast()
        }
        
    }
    
    //7
    if newID.count <= 2 {
        
        while newID.count != 3 {
            newID = newID + String(newID.last!)
        }
        
    }
    
    return newID
}

좋은 웹페이지 즐겨찾기