코딩테스트
숫자 문자열과 영단어
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 를 통해 문자열을 바꿀수 있다.