优化在长Swift字符串中添加破折号

瑞安·滕斯迈尔

我正在尝试使用十六进制字符串,并在其他所有字符之间插入破折号(例如,“ b201a968”至“ b2-01-a9-68”)。我发现了几种解决方法,但问题是我的字符串相当大(8066个字符),而且我能最快地使它起作用,仍然需要几秒钟。这些是我尝试过的方法以及花费了多长时间。谁能帮助我优化此功能?

//42.68 seconds
    func reformatDebugString(string: String) -> String
    {
        var myString = string
        var index = 2
        while(true){
            myString.insert("-", at: myString.index(myString.startIndex, offsetBy: index))
            index += 3
            if(index >= myString.characters.count){
                break
            }
        }

        return myString
    }

//21.65 seconds
    func reformatDebugString3(string: String) -> String
    {
        var myString = ""
        let length = string.characters.count
        var first = true
        for i in 0...length-1{
            let index = string.index(myString.startIndex, offsetBy: i)
            let c = string[index]

            myString += "\(c)"
            if(!first){
                myString += "-"
            }
            first = !first
        }

        return myString
    }

//11.37 seconds
    func reformatDebugString(string: String) -> String
    {
        var myString = string
        var index = myString.characters.count - 2
        while(true){
            myString.insert("-", at: myString.index(myString.startIndex, offsetBy: index))
            index -= 2
            if(index == 0){
                break
            }
        }

        return myString
    }
OOPer

正如Hamish的回答中已经指出的那样,您应该避免以下两件事:

  • 计算每个索引 string.index(string.startIndex, offsetBy: ...)
  • 用修改大字符串 insert(_:at:)

因此,这可以是另一种方式:

func reformatDebugString4(string: String) -> String {
    var result = ""

    var currentIndex = string.startIndex
    while currentIndex < string.endIndex {
        let nextIndex = string.index(currentIndex, offsetBy: 2, limitedBy: string.endIndex) ?? string.endIndex
        if currentIndex != string.startIndex {
            result += "-"
        }
        result += string[currentIndex..<nextIndex]
        currentIndex = nextIndex
    }

    return result
}

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

在字符串的某些位置添加破折号(Javascript)

Python为字符串中的字符添加破折号?

Java删除字符串数组中的破折号

替换Java字符串中的破折号

字符串插补中的格式破折号

从Bash中的字符串末尾删除破折号

如何从字符串中删除'em'破折号?

Oracle REGEXP_REPLACE帮助在数字字符串中添加破折号

为什么带有长字符串的选项带有双破折号?

在数字字符串中添加破折号的一种优雅方法是什么?

如何用双破折号和/或单破折号匹配字符串?

Java中的拆分字符串包含破折号/连字符

当 SQL Server 中的字符串太长时,如何添加破折号来分隔字符串?我需要编写脚本,而不是对其进行硬编码...谢谢

从破折号(-)之后的字符串中提取数值

休眠搜索与破折号字符串完全匹配

从不带破折号的字符串创建UUID

xlabel转换为破折号字符串

使用破折号的MySQL字符串匹配

测量破折号之间字符串的 LEN

用破折号 (-) python 分割字符串

从pandas Dataframe中的混合dtype列中删除破折号字符串

从带破折号的字符串中解析熊猫列的日期

在Graylog中搜索带有破折号和数字的字符串?

从后面的字符串中删除破折号还是删除键?

substr 与字符串中的破折号一起奇怪地工作

在javascript字符串中的破折号后获取所有内容

如何在bash printf的格式字符串中包含破折号?

验证/检查字符串中破折号后的值

Javascript Regex删除数字中破折号周围的空格而不是字符串