Created
July 19, 2021 08:13
-
-
Save yycking/94c6db4d23341aebcefbece30cacf5d9 to your computer and use it in GitHub Desktop.
數字轉中文大寫(最大單位只能換到萬)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
extension String { | |
subscript(_ i: Int) -> String { | |
let idx1 = index(startIndex, offsetBy: i) | |
let idx2 = index(idx1, offsetBy: 1) | |
return String(self[idx1..<idx2]) | |
} | |
subscript (r: Range<Int>) -> String { | |
let start = index(startIndex, offsetBy: r.lowerBound) | |
let end = index(startIndex, offsetBy: r.upperBound) | |
return String(self[start ..< end]) | |
} | |
subscript (r: CountableClosedRange<Int>) -> String { | |
let startIndex = self.index(self.startIndex, offsetBy: r.lowerBound) | |
let endIndex = self.index(startIndex, offsetBy: r.upperBound - r.lowerBound) | |
return String(self[startIndex...endIndex]) | |
} | |
} | |
let number = "10".reversed() | |
let symbol = [ | |
"","拾", "佰", "仟", "萬" | |
] | |
let chinese = "零壹貳參肆伍陸柒捌玖" | |
var result = number.map { (char) -> String in | |
let index = Int(String(char)) | |
return chinese[index ?? 0] | |
} | |
for i in 1 ..< result.count { | |
if result[i] == "零" { | |
if result[i-1] == "零" { | |
result[i-1] = "" | |
} | |
}else { | |
result[i] += symbol[i] | |
} | |
} | |
var text = result.reversed().joined() | |
if text.count > 1, text.hasSuffix("零") { | |
text.removeLast() | |
} | |
print(text) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
另一種寫法
原生spell為小寫,需轉大寫