[英]How to check if a string contains only allowed characters in Swift
I've searched a way to check in Swift if a string contains particular characters and just them.我已经搜索了一种方法来检查 Swift 是否一个字符串包含特定字符并且只包含它们。 For exemple, if a string contains them but it contains other characters as well, it should return false
.例如,如果一个字符串包含它们但它也包含其他字符,它应该返回false
。
What I need is something which allows me to say if a string contains JUST some elements.我需要的是可以让我判断一个字符串是否只包含一些元素的东西。 For exemple: If I wanna know if "101010010101"
contains ONLY 1 and 0 it should return true
.例如:如果我想知道"101010010101"
是否只包含 1 和 0,它应该返回true
。 But "1901919117"
doesn't contains ONLY 1 and 0 it should return false
.但是"1901919117"
不只包含 1 和 0 它应该返回false
。
Maybe You could go with something like this (just check if Your allowed characters are super set of Your string):也许你可以 go 这样的东西(只要检查你允许的字符是否是你的字符串的超集):
import Foundation
let allowedChars = Set("10")
print(allowedChars)
let a = "101010010101"
let b = "1901919117"
print(allowedChars.isSuperset(of: a)) //prints true
print(allowedChars.isSuperset(of: b)) //prints false
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.