我想在Swift中将字符串拆分为两个符号。所以在字符串“df57g5df7g”之后我想获得一个数组[“df”,“57”,“g5”,“df”,“7g”]。 是否可以强制使用迭代器
for i in word.characters {
print(i)
}
跳过两个符号,并获得循环中的下一个符号?
答案 0 :(得分:5)
一个简单的while
循环:
let str = "df57g5df7g"
var startIndex = str.startIndex
var result = [String]()
repeat {
let endIndex = startIndex.advancedBy(2, limit: str.endIndex)
result.append(str[startIndex..<endIndex])
startIndex = endIndex
} while startIndex < str.endIndex
print(result)
或者更多的东西:
let result = 0.stride(to: str.characters.count, by: 2).map { i -> String in
let startIndex = str.startIndex.advancedBy(i)
let endIndex = startIndex.advancedBy(2, limit: str.endIndex)
return str[startIndex..<endIndex]
}
答案 1 :(得分:1)
这可能不是最简单的解决方案,但它有效:
var word = "df57g5df7g"
var pairsArray = [String]()
while word.characters.count > 1 {
let firstCharacter = word.removeAtIndex(word.startIndex)
let secondCharacter = word.removeAtIndex(word.startIndex)
pairsArray.append("\(firstCharacter)\(secondCharacter)")
}
print(pairsArray)
结果是:
["df", "57", "g5", "df", "7g"]
答案 2 :(得分:1)
这是我见过的最佳解决方案,取自SwiftSequence
library。
extension CollectionType {
public func chunk(n: Index.Distance) -> [SubSequence] {
var res: [SubSequence] = []
var i = startIndex
var j: Index
while i != endIndex {
j = i.advancedBy(n, limit: endIndex)
res.append(self[i..<j])
i = j
}
return res
}
}
let word = "df57g5df7g"
let pairs = word.characters.chunk(2).map(String.init)
print(pairs) //["df", "57", "g5", "df", "7g"]
您可以在行动here中看到它。