0

I have to find 1 of 3 characters in a string. How can I do that?

I tried this:

let value = "from 3,95 €"
let wanted: Character = "£", "€" OR "₹"
if let idx = value.characters.index(of: wanted) {                                    
    print("Found \(wanted)")
} else {
    print("Not found")
}

Thank you!

LinusGeffarth
  • 27,197
  • 29
  • 120
  • 174
Saintz
  • 69
  • 7
  • You just want to check String having that character or not, right or you want index of that character also ? – Nirav D Jun 19 '17 at 06:16
  • Any reason for why you don't use `NSNumberFormatter`? Check this [documentation](https://developer.apple.com/documentation/foundation/numberformatter). – LinusGeffarth Jun 19 '17 at 06:16
  • @Nirav D: Yes, i just want to check if one of these characters in a string or not. No i don't need the index.... – Saintz Jun 19 '17 at 06:21
  • @Saintz see [my answer](https://stackoverflow.com/a/44623471/3687801) below – nayem Jun 19 '17 at 06:42
  • Possible duplicate of [What is the best way to determine if a string contains a character from a set in Swift](https://stackoverflow.com/questions/28486138/what-is-the-best-way-to-determine-if-a-string-contains-a-character-from-a-set-in) – nayem Jun 19 '17 at 07:01

3 Answers3

1

Don't exactly know what you want achieve but if you want to know which character string contains from these 3 character then you can make something like this.

let value = "from 3,95 €"
let wanted: [Character] = ["£", "€", "₹"]
if let result = value.characters.first(where: { wanted.contains($0) }) {
    print("Found \(result)")
} else {
    print("Not found")
}

Output

Found €

Edit: If you just want to check the string contains then use contains(where:) instead of first(where:)

if value.characters.contains(where: { wanted.contains($0) }) {
    print("Found")
} else {
    print("Not found")
}
Nirav D
  • 71,513
  • 12
  • 161
  • 183
1

Swift 3:

if let dataArray = value.characters.filter{ $0 == "£" || $0 == "€" || $0 == "₹" }, dataArray.count > 0 {
//you have at least one of them in your string, so do whatever you want here
}
Mina
  • 2,167
  • 2
  • 25
  • 32
  • Sorry, one more question. And if i want to find no one of these characters in the string is it ??? : !value.characters.filter{ $0 == "£" || $0 == "€" || $0 == "₹" }, dataArray.count > 0 {... – Saintz Jun 19 '17 at 06:54
  • you can use ```else {}``` statement. ```if let dataArray = ... > 0 {} else {//None of them found}``` – Mina Jun 19 '17 at 07:01
0

Try this if you want to just determine whether they exists or not:

let value = "from 3,95 €"
let wanted = CharacterSet(charactersIn: "£€₹")
if value.rangeOfCharacter(from: wanted) != nil {
    print("Found")
} else {
    print("Not found")
}
nayem
  • 7,285
  • 1
  • 33
  • 51