Geon

숫자 문자열과 영단어 본문

코딩테스트

숫자 문자열과 영단어

jgkim1008 2022. 3. 15. 05:40

해결 코드


func solution(_ s:String) -> Int {
    let array = ["zero", "one","two","three","four","five","six","seven","eight","nine"]
    var result = s
    for i in 0..<array.count{
        result = result.replacingOccurrences(of: array[i], with: String(i)) 
    }
    return Int(result) ?? .zero

}
print(solution("one4seveneight"))

 



func solution(_ s:String) -> Int {
    var result = s
    result = result.replacingOccurrences(of: "zero", with: "0")
        .replacingOccurrences(of: "one", with: "1")
        .replacingOccurrences(of: "two", with: "2")
        .replacingOccurrences(of: "three", with: "3")
        .replacingOccurrences(of: "four", with: "4")
        .replacingOccurrences(of: "five", with: "5")
        .replacingOccurrences(of: "six", with: "6")
        .replacingOccurrences(of: "seven", with: "7")
        .replacingOccurrences(of: "eight", with: "8")
        .replacingOccurrences(of: "nine", with: "9")
    return Int(result) ?? .zero
}
print(solution("one4seveneight"))

배운점

.replacingOccurrences 를 통해 문자열을 바꿀수 있다.

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

단어뒤집기[BOJ]  (0) 2022.03.22
스택[BOJ]  (0) 2022.03.22
신고 결과 받기  (0) 2022.03.18
로또의 최고 순위와 최저 순위  (0) 2022.03.16
신규 아이디 추천  (0) 2022.03.15