Reputation: 69
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!
Upvotes: 0
Views: 58
Reputation: 2212
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
}
Upvotes: 1
Reputation: 72450
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")
}
Upvotes: 1
Reputation: 7605
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")
}
Upvotes: 0