Swift-银行卡格式转换

作者: FlyElephant | 来源:发表于2018-01-30 14:51 被阅读44次

    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())")
    

    相关文章

      网友评论

        本文标题:Swift-银行卡格式转换

        本文链接:https://www.haomeiwen.com/subject/rlhnrxtx.html