Swift 项目开发中遇到将银行卡按照4位一组,中间空格的形式展示,扩展了String类,扩展方法如下:
public func formateForBankCard(joined: String = " ") -> String {
guard self.characters.count > 0 else {
return self
}
let length: Int = self.characters.count
let count: Int = length / 4
var data: [String] = []
for i in 0..<count {
let start: Int = 4 * i
let end: Int = 4 * (i + 1)
data.append(self[start..<end])
}
if length % 4 > 0 {
data.append(self[4 * count..<length])
}
let result = data.joined(separator: " ")
return result
}
测试代码:
print("输出结果:\("123456789".formateForBankCard())")
网友评论