코딩테스트
신규 아이디 추천
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:) 로 원하는 문자열 길이를 잘라낼수 있다.