在處理身分證字號時,有時使用者會不小心輸入全型的文字,或者我們要以全型的文字顯示地址等資訊。而在 Swift 中,我們如何將字串在全型和半型之間轉換呢?其實很簡單呢!快看這一篇文章,你馬上就會了!
![[Swift] 如何將字串在全型和半型之間轉換 1 swift](https://www.inote.tw/wp-content/uploads/2020/02/swift-1.png)
首先,我們先來寫一個字串的擴充。
extension String {
///轉半形
var halfWidth: String {
transformFullWidthToHalfWidth(reverse: false)
}
///轉全型
var fullWidth: String {
transformFullWidthToHalfWidth(reverse: true)
}
private func transformFullWidthToHalfWidth(reverse: Bool) -> String {
let string = NSMutableString(string: self) as CFMutableString
CFStringTransform(string, nil, kCFStringTransformFullwidthHalfwidth, reverse)
return string as String
}
}
那麼,接下來你會怎麼用呢?就依底下的用法用就好了。
var str = "Hello, playground"
print(str.fullWidth)
// Hello, playground
會這麼簡單的原因是在於我們在 halfWidth 時就已經呼叫「transformFullWidthToHalfWidth」將文字做全型和半型之間的轉換了,所以我們只要聰明地利用擴充,就可以將程式寫的更簡單唷!