【问题标题】:Swift: Repeating letters turn to a number in a String [closed]斯威夫特:重复字母变成字符串中的数字[关闭]
【发布时间】:2019-02-05 12:27:06
【问题描述】:

我有一个字符串,可以说

var abc : String = "aaaabbbbbbbccddd"

我需要一个算法来将这些重复字母更改为重复字母的数量(如果连续超过 2 个),这样给定的字符串就会变成

abc = "a4b7ccd3"

任何提示将不胜感激。

【问题讨论】:

    标签: ios swift string


    【解决方案1】:

    让我们从这个字符串开始:

    let abc : String = "aaaabbbbbbbccddde"
    

    并将输出放在一个新变量中

    var result = ""
    

    让我们使用索引来遍历字符串中的字符

    var index = abc.startIndex
    
    while index < abc.endIndex {
        //There is already one character :
        let char = abc[index]
        var count = 0
    
        //Let's check the following characters, if any
        repeat {
            count += 1
            index = abc.index(after: index)
        } while index < abc.endIndex && abc[index] == char
    
        //and update the result accordingly 
        result += count < 3 ?
            String(repeating: char, count: count) :
            String(char) + String(count)
    }
    

    结果如下:

    print(result)  //a4b7ccd3e
    

    【讨论】:

    • 小注:内层循环使用repeat {} while可以稍微缩短,避免重复索引增量。
    • @MartinR:好主意!我会根据您的建议更新答案
    猜你喜欢
    • 2018-12-29
    • 1970-01-01
    • 2023-03-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多