Algorithm/프로그래머스

[프로그래머스 스위프트] 숫자 문자열과 영단어

devKen 2022. 9. 13. 21:10

아이디어

replacingOccurrences(of: "old", with: "new") 메서드를 알고 있냐 모르냐가 난이도를 결정짓는 문제이다.

다소 품위없게 if를 도배하면서 풀었는데 풀고 나서 다른 사람들의 풀이를 보니까 굳이 이렇게 풀 필요가 없었다. replacingOccurrences 메서드의 of에 해당 문자열이 없으면 변환을 진행시키지 않는다. 또한 .으로 연속해서 변환을 수행할 수도 있었다.

해답

import Foundation

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

    return Int(s)!
}