最近一个朋友问了我一个问题,怎么将
005056b12cda
变成00:50:56:b1:2c:da
规律:按照一定的长度逐步分割字符串,并用特定的分割符将这些小段的字符串连成一个新的字符串
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.
你可以使用此函数跨过遵循
Strideable
协议的任何类型的值,例如整数或浮点类型。从start开始,序列的每个连续值都会增加步幅,直到下一个值等于或超过end
2.可是String
类型没有遵循Strideable
协议,不能直接进行stride
操作,但是Array
遵循该协议,而正好String
也是集合类型,我们可以先将字符串转成Array
,进行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: ":")
Playground运行结果
网友评论