你如何在Swift的每个第n个字符中拆分一个字符串?

时间:2018-05-02 07:11:46

标签: swift

就像问题所说,如果我有:

XQQ230IJFEKJLDSAIOUOIDSAUIFOPDSFE28

如何在每第8个字符处拆分此字符串以获取:

XQQ230IJ FEKJLDSA IOUOIDSA UIFOPDSA

1 个答案:

答案 0 :(得分:0)

实施此功能

extension String {
    func inserting(separator: String, every n: Int) -> String {
        var result: String = ""
        let characters = Array(self.characters)
        stride(from: 0, to: characters.count, by: n).forEach {
            result += String(characters[$0..<min($0+n, characters.count)])
            if $0+n < characters.count {
                result += separator
            }
        }
        return result
    }
}

这样称呼,

let str = "XQQ230IJFEKJLDSAIOUOIDSAUIFOPDSFE28"
let final = str.inserting(separator: " ", every: 8)
print(final)

输出将是这样的,

XQQ230IJ FEKJLDSA IOUOIDSA UIFOPDSF E28

如果您想添加任何字符而不是空格,这将是通用解决方案,它将起作用。