Swift:重复的字母变成字符串中的数字 [英] Swift: Repeating letters turn to a number in a String

查看:97
本文介绍了Swift:重复的字母变成字符串中的数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个字符串,可以说

I have a String, lets say

var abc : String = "aaaabbbbbbbccddd"

我需要一种算法,用于将这些重复字母更改为重复字母的数量(如果连续超过2个),以使给定的字符串变为

I need an algorithm on how to change these repeating letters to the number of repeating letters (if there is more than 2 in a row), so that the given string would become

abc = "a4b7ccd3"

任何提示将不胜感激.

推荐答案

让我们从以下字符串开始:

Let's start with this string :

let abc : String = "aaaabbbbbbbccddde"

并在新变量中添加输出

var result = ""

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

Let's use an index to go through the characters in the string

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

这篇关于Swift:重复的字母变成字符串中的数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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