這就是我從頭頂上想出來的。我敢打賭,有一個更好的方式來做這件事,所以我鼓勵你繼續嘗試。
func splitedString(string: String, length: Int) -> [String] {
var groups = [String]()
var currentGroup = ""
for index in string.startIndex..<string.endIndex {
currentGroup.append(string[index])
if currentGroup.characters.count == 3 {
groups.append(currentGroup)
currentGroup = ""
}
}
if currentGroup.characters.count > 0 {
groups.append(currentGroup)
}
return groups
}
這裏是我的測試
let firstString = "123456789"
let groups = splitedString(firstString, length: 3)
// Returned ["123", "456", "789"]
let secondString = "1234567"
let moreGroups = splitedString(secondString, length: 3)
// Returned ["123", "456", "7"]
的目標是什麼和什麼樣的約束?您是否嘗試對數字表示進行格式化,例如:「10000」會變成「10 000」? – Moritz
@EricD。不,'NSNumberFormatter'不是我的情況。我只想知道,我可以通過split()函數或其他一些不錯的解決方案來實現這個功能。 – katleta3000
請注意完全相同(因爲* last * chunk被截斷,而不是您的示例中的第一個),但可能將服務器作爲起點:stackoverflow.com/a/28560013/1187415。 –