将字符串拆分为每个数组中包含最大变量的数组

时间:2017-12-25 14:04:46

标签: swift string

我有一串数字(每个数字用,分隔),如下所示:

"12,3,5,75,584,364,57,88,94,4,79,333,7465,867,56,6,748,546,573,466"

我想将字符串拆分为一个字符串数组,每个元素都是一个字符串,其中包含最多10个数字。

对于我添加的示例,我想要实现这样的目标:

stringsArray:

Element 0: "12,3,5,75,584,364,57,88,94,4"
Element 1: "79,333,7465,867,56,6,748,546,573,466"

等等......

我一直在考虑用Swift做这个的方法,但找不到任何东西......

有人有想法吗?

谢谢!

2 个答案:

答案 0 :(得分:3)

第1步 - 获得完全分离的数组:

let numbers = "12,3,5".components(separatedBy: ",")

第2步 - 将结果分块到ext:

extension Array {
    func chunked(by chunkSize: Int) -> [[Element]] {
        return stride(from: 0, to: self.count, by: chunkSize).map {
            Array(self[$0..<Swift.min($0 + chunkSize, self.count)])
        }
    }
}

let chunkedNumbers = numbers.chunked(by: 10)

第3步:

let stringsArray = chunkedNumbers.map { $0.joined(separator: ",") }

结果:["12,3,5,75,584,364,57,88,94,4", "79,333,7465,867,56,6,748,546,573,466"]

链接到gist playground.

答案 1 :(得分:0)

我会查看原始字符串中第10个逗号的位置,获取前缀到此位置,删除此前缀并重复直到剩余的字符串为空。

这有点暴力,但有效。

为方便起见,我首先向String添加扩展名。

extension String {

func startIndexesOf(_ string: String) -> [Int] {
    var result: [Int] = []
    var start = startIndex
    while let range = range(of: string, options: .literal, range: start..<endIndex) {
        result.append(range.lowerBound.encodedOffset)
        start = range.upperBound
    }
    return result
}

subscript (r: Range<Int>) -> String {
    let start = index(self.startIndex, offsetBy: r.lowerBound)
    let end = self.index(self.startIndex, offsetBy: r.upperBound)
    return String(self[Range(start ..< end)])
    }
}

let test = "12,3,5,75,584,364,57,88,94,4,79,333,7465,867,56,6,748,546,573,466,999"
var remaining = test
var arrayOf10 : [String] = []

repeat {
    let indexes = remaining.startIndexesOf(",")
    if indexes.count < 10 {
        arrayOf10.append(remaining) // Just add what remains
        break
   }

   let position = indexes[9]

   let endBeginning = remaining.index(test.startIndex, offsetBy: position)  // Beginning of what remain to parse
   let beginningSubstring = remaining[remaining.startIndex ..< endBeginning]
   let beginningText = String(beginningSubstring)
   arrayOf10.append(beginningText)

   let startNext = remaining.index(test.startIndex, offsetBy: position+1)  // What will remain to parse after taking out the beginning
   let remainingSubString = remaining[startNext ..< remaining.endIndex]
   remaining = String(remainingSubString)

} while remaining.count > 0

for (c, s) in arrayOf10.enumerated() { print("Element", c, ": ", s)}

这将根据需要打印

Element 0 :  12,3,5,75,584,364,57,88,94,4
Element 1 :  79,333,7465,867,56,6,748,546,573,466
Element 2 :  999