最近一個(gè)朋友問(wèn)了我一個(gè)問(wèn)題,怎么將
005056b12cda
變成00:50:56:b1:2c:da
規(guī)律:按照一定的長(zhǎng)度逐步分割字符串扁掸,并用特定的分割符將這些小段的字符串連成一個(gè)新的字符串
1.stride(from:to:by:)
官方文檔
//Returns a sequence from a starting value to, but not including, an end value, stepping by the specified amount.
func stride<T>(from start: T, to end: T, by stride: T.Stride) -> StrideTo<T>where T : Strideable
You can use this function to stride over values of any type that conforms to the Strideable protocol, such as integers or floating-point types. Starting with start, each successive value of the sequence adds stride until the next value would be equal to or beyond end.
你可以使用此函數(shù)跨過(guò)遵循
Strideable
協(xié)議的任何類型的值,例如整數(shù)或浮點(diǎn)類型税产。從start開(kāi)始辐益,序列的每個(gè)連續(xù)值都會(huì)增加步幅,直到下一個(gè)值等于或超過(guò)end
2.可是String
類型沒(méi)有遵循Strideable
協(xié)議肄满,不能直接進(jìn)行stride
操作谴古,但是Array
遵循該協(xié)議,而正好String
也是集合類型稠歉,我們可以先將字符串轉(zhuǎn)成Array
掰担,進(jìn)行stride
后遍歷的到的序列,再將元素拼接成我們想要的字符串:
//swift 4.0+
extension Array {
func chunked(into size: Int) -> [[Element]] {
return stride(from: 0, to: count, by: size).map {
Array(self[$0 ..< Swift.min($0 + size, count)])
}
}
}
extension String {
func chunked(into size: Int, separatedBy separator: String) -> String {
let array = Array(self)
let newArray = array.chunked(into: size)
var newString = ""
for (index, item) in newArray.enumerated() {
if index == 0 {
newString = String(item)
} else {
newString += separator + String(item)
}
}
return newString
}
}
let str = "005056b12cda"
str.chunked(into: 2, separatedBy: ":")