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



我在Swift中遇到了一个关于字符串替换的问题。web服务器通过XML进行通信,文件以base64编码并通过XML发送。我有一些助手函数,它获取一个XML模板,替换一些头,然后用base64编码的二进制数据(图像、文档(替换#data#。

同样的操作在Android上几乎是即时的。在iOS上,由于某些原因,它需要更长的时间。在CPU使用率为100%的情况下,返回最终的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"现在使用replacingOccurrences(of:",with:"(,我可以用-替换空白

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

那么结果将是:

Hello-World

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

最新更新