如何获取字符串中不同字符的#? (Swift 4.2 + )
How to get # of distinct characters in a string? (Swift 4.2 + )
此算法或代码应该适用于字符串中任意 # 个唯一字符,根据我们用于检查的条件。
例如(如果我有一个字符串,我想知道我们是否至少有 7 个唯一字符,我们可以这样做):
let number_of_distinct = Set(some_string.characters).count
if(number_of_distinct >= 7)
{
// yes we have at least 7 unique chars.
}
else
{
// no we don't have at least 7 unique chars.
}
但是,由于 Swift 4.0 + 中更新字符串的方式,此技术似乎在 Swift 4.2 + 中被弃用。
上述技术的正确新方法是什么?
只需删除 .characters
let number_of_distinct = Set(some_string).count
if(number_of_distinct >= 7)
{
print("yes")
// yes we have at least 7 unique chars.
}
else
{
print("no")
// no we don't have at least 7 unique chars.
}
您也可以在不使用 Set 的情况下执行此操作。
func printUniqueCompleteSubString(from string: String) {
var uniquString = ""
uniquString = string.reduce(uniquString) { (result, char) -> String in
if result.contains(char) {
return result
}
else {
return result + String.init(char)
}
}
print("Unique String is:", uniquString)
}
此算法或代码应该适用于字符串中任意 # 个唯一字符,根据我们用于检查的条件。
例如(如果我有一个字符串,我想知道我们是否至少有 7 个唯一字符,我们可以这样做):
let number_of_distinct = Set(some_string.characters).count
if(number_of_distinct >= 7)
{
// yes we have at least 7 unique chars.
}
else
{
// no we don't have at least 7 unique chars.
}
但是,由于 Swift 4.0 + 中更新字符串的方式,此技术似乎在 Swift 4.2 + 中被弃用。
上述技术的正确新方法是什么?
只需删除 .characters
let number_of_distinct = Set(some_string).count
if(number_of_distinct >= 7)
{
print("yes")
// yes we have at least 7 unique chars.
}
else
{
print("no")
// no we don't have at least 7 unique chars.
}
您也可以在不使用 Set 的情况下执行此操作。
func printUniqueCompleteSubString(from string: String) {
var uniquString = ""
uniquString = string.reduce(uniquString) { (result, char) -> String in
if result.contains(char) {
return result
}
else {
return result + String.init(char)
}
}
print("Unique String is:", uniquString)
}