Skip to content

Instantly share code, notes, and snippets.

@sgr-ksmt
Last active July 15, 2021 18:55
Show Gist options
  • Save sgr-ksmt/2dcf11a64cdb22d44517 to your computer and use it in GitHub Desktop.
Save sgr-ksmt/2dcf11a64cdb22d44517 to your computer and use it in GitHub Desktop.
[Swift] : 文字列の全角/半角の変換 + 数字だけ半角/全角変換
extension String {
private func convertFullWidthToHalfWidth(reverse: Bool) -> String {
let str = NSMutableString(string: self) as CFMutableString
CFStringTransform(str, nil, kCFStringTransformFullwidthHalfwidth, reverse)
return str as String
}
var hankaku: String {
return convertFullWidthToHalfWidth(false)
}
var zenkaku: String {
return convertFullWidthToHalfWidth(true)
}
private func convertFullWidthToHalfWidthOnlyNumber(fullWidth: Bool) -> String {
var str = self
let pattern = fullWidth ? "[0-9]+" : "[0-9]+"
let regex = try! NSRegularExpression(pattern: pattern, options: [])
let results = regex.matchesInString(str, options: [], range: NSMakeRange(0, str.characters.count))
results.reverse().forEach {
let subStr = (str as NSString).substringWithRange($0.range)
str = str.stringByReplacingOccurrencesOfString(
subStr,
withString: (fullWidth ? subStr.zenkaku : subStr.hankaku))
}
return str
}
var hankakuOnlyNumber: String {
return convertFullWidthToHalfWidthOnlyNumber(false)
}
var zenkakuOnlyNumber: String {
return convertFullWidthToHalfWidthOnlyNumber(true)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment