使用Swift在64kb中拆分字符串 [英] Split string in 64kb using Swift

查看:105
本文介绍了使用Swift在64kb中拆分字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想用64kb块分割一个非常大的字符串,最大为8mb。目前我正在使用以下代码:

I would like to split an extremely large string, up to 8mb, in 64kb chunks. At the moment I am using the following code:

//1
var regData:String= "string up to 8mb"
var count=((countElements(self.regData!))/65536)

//2
for var index = 0; index < count; ++index {
    arr.append(self.regData!.substringWithRange(Range<String.Index>(start: advance(self.regData!.startIndex, 0),end: advance(self.regData!.startIndex, 65536))))
    self.regData!.removeRange(Range<String.Index>(start: self.regData!.startIndex, end:advance(self.regData!.startIndex, 65536)))
    println(index)
 }
//3
println("exit loop")
arr.append(self.regData!)




  1. 我计算了我有多少64 kb的块。

  2. In for循环我获得了第一个64kb。我在一个数组中收集它们。现在我必须删除第一个64kb字符串,因为第3步。

  3. 如果我的数量少于64kb,我的循环中会出错。因此,我的最后一步是在循环之外。

代码工作正常,但速度非常慢。我需要加快我的代码。你知道怎么做吗?

The code works fine, but it is extremely slow. I need to speed up my code. Do you have any idea how to do it.

谢谢你。

推荐答案

如果你不修改原始字符串
并且只使用两个索引(来自),它可能会更有效到)遍历字符串:

It might be more effective if you don't modify the original string, and just use two indices (from and to) to traverse through the string:

let regData = "string up to 8mb"
let chunkSize = 65536

var array = [String]()
var from = regData.startIndex // start of current chunk
let end = regData.endIndex    // end of string
while from != end {
    // advance "from" by "chunkSize", but not beyond "end":
    let to = from.advancedBy(chunkSize, limit: end)
    array.append(regData.substringWithRange(from ..< to))
    from = to
}

请注意,这会给出65536个字符的子字符串。由于Swift
字符代表Unicode字形集群,因此
不会对应64kB数据。如果你需要那么你应该将
的字符串转换为 NSData 并将其拆分成块。

Note that this gives substrings of 65536 characters. Since a Swift character represents a "Unicode grapheme cluster", this will not correspond to 64kB of data. If you need that then you should convert the string to NSData and split that into chunks.

(针对Swift 2更新。)

这篇关于使用Swift在64kb中拆分字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆