0

I've searched a way to check in Swift if a string contains particular characters and just them. For exemple, if a string contains them but it contains other characters as well, it should return 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. But "1901919117" doesn't contains ONLY 1 and 0 it should return false.

Leo Dabus
  • 229,809
  • 59
  • 489
  • 571
  • 1
    Hi, please take a look [how to ask a good question](https://stackoverflow.com/help/how-to-ask). As far from Your problem, I suggest You to first try some search on SO. I am quite sure You will find an answer that already answers this question. – Whirlwind Feb 27 '22 at 22:40
  • I already searched but didn't find... – Ghaly Sekkat Feb 27 '22 at 22:47
  • Ok, well, Your question is a bit unclear, at least You can add an example of possible input(s)/output(s). Maybe You could use [this](https://stackoverflow.com/a/59823657/3402095) – Whirlwind Feb 27 '22 at 23:01
  • `"abc".contains(where: "123".contains)` would return false `"abc1".contains(where: "123".contains)` would return true – Leo Dabus Feb 27 '22 at 23:03
  • But what I'm searching for is something which permit me to say if sth contain JUST some elements. For exemple : \ If i wanna know if 101010010101 contains JUST 1 and 0 it's true \ But 1901919117 doesn't contain JUST 1 and 0 – Ghaly Sekkat Feb 27 '22 at 23:14
  • 2
    @GhalySekkat `"101010010101".allSatisfy("01".contains)` // true or use a Set of characters as suggested by @Whirlwind – Leo Dabus Feb 27 '22 at 23:54

1 Answers1

4

Maybe You could go with something like this (just check if Your allowed characters are super set of Your string):

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
Whirlwind
  • 14,286
  • 11
  • 68
  • 157