小编Dew*_*ime的帖子

在 Swift 中使用 for-in 循环检查字符串中的重复字符

我使用 while 循环做到了这一点,但我想知道是否有办法用 for 循环做到这一点。我正在尝试将其写得干净,以便我可以将其写在白板上以便人们理解。

var str = "Have a nice day"

func unique(_ str: String) -> String {
    var firstIndex = str.startIndex

    while (firstIndex != str.endIndex) {
        var secondIndex = str.index(after: firstIndex)

        while (secondIndex != str.endIndex) {
            if (str[firstIndex] == str[secondIndex]) {
                return "Not all characters are unique"
            }
            secondIndex = str.index(after: secondIndex)
        }
        firstIndex = str.index(after: firstIndex)
    }
    return "All the characters are unique"
}

print("\(unique(str))")
Run Code Online (Sandbox Code Playgroud)

string loops swift

5
推荐指数
1
解决办法
8218
查看次数

标签 统计

loops ×1

string ×1

swift ×1