Last active
July 15, 2021 18:55
-
-
Save sgr-ksmt/2dcf11a64cdb22d44517 to your computer and use it in GitHub Desktop.
[Swift] : 文字列の全角/半角の変換 + 数字だけ半角/全角変換
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 { | |
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