繁体   English   中英

如何在 Swift 中使用 base64 文件优化字符串替换?

[英]How can I optimize string replacement in Swift with base64 file in it?

我对 Swift 中的字符串替换有疑问。 Web 服务器通过 XML 进行通信,文件以 base64 编码并通过 XML 发送。 我有一些辅助函数,它们获取 XML 模板、替换一些标题,然后用 base64 编码的二进制数据(图像、文档)替换 #data#。

Android 上的相同操作几乎是即时的。 在 iOS 上由于某种原因,它需要更长的时间。 在 100% CPU 使用率下返回最终的 XML 大约需要 1.6 秒。 实时时间大约为 4 秒。 它也运行在后台线程上...

 local = insertHeaders(xml: local)
 local = local.replace(this: "#type#", with: "saveoperation")
 local = local.replace(this: "#id#", with: id)
 local = local.replace(this: "#data#", with: xmlData.getEncryptedString)

String.replace 函数取自此处:

func replace(this pattern : String, with newValue: String) -> String {
        let regex = try! NSRegularExpression(pattern: pattern)
        let range = NSMakeRange(0, self.count)
        let modString = regex.stringByReplacingMatches(in: self, options: [], range: range, withTemplate: newValue)
        return modString
}

有什么有效的方法可以替换字符串中的文本?

只需使用 String.replacingOccurrences()。 我将时间从 1.6 秒减少到 0.4 秒!

您可以使用

replacingOccurrences(of: "", with: "")

例如:

让 myString = "Hello World" 现在使用replaceOccurrences(of: "", with: "") 我可以用-替换空格 -

let result = myString.replacingOccurrences(of: " ", with: "-")

那么结果将是:

Hello-World

并且您可以使用相同的方法更改特定单词

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM