我使用 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)