Home Swift 全角半角转换
Post
Cancel

Swift 全角半角转换

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
import Foundation

extension String {
    // 全角字符串转为半角字符串
    public var halfwidthString: String {
        let text:CFMutableString = NSMutableString(string: self) as CFMutableString
        CFStringTransform(text, nil, kCFStringTransformFullwidthHalfwidth, false)
        return text as String
    }
    
    // 半角字符串转为全角字符串
    public var fullwidthString: String {
        let text:CFMutableString = NSMutableString(string: self) as CFMutableString
        CFStringTransform(text, nil, kCFStringTransformFullwidthHalfwidth, true)
        return text as String
    }
}

其他类型的字符串转换类似,具体可查阅 官方文档

This post is licensed under CC BY 4.0 by the author.