3

How do I check if a String includes a specific Character?

For example:

if !emailString.hasCharacter("@") {
    println("Email must contain at sign.")
}
Eric Aya
  • 69,473
  • 35
  • 181
  • 253
ma11hew28
  • 121,420
  • 116
  • 450
  • 651
  • 2
    Note, not a duplicate of [this question](http://stackoverflow.com/q/25957594/3925941) since that is checking if a string contains another string, not a character. – Airspeed Velocity Jun 23 '15 at 15:51

3 Answers3

4

You can use the free-standing find function, like this:

let s = "hello"
if (find(s, "x") != nil) {
    println("Found X")
}
if (find(s, "l") != nil) {
    println("Found L")
}
pteofil
  • 4,133
  • 17
  • 27
Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
  • 2
    Note for anyone upgrading to Swift 2, this would now be `if s.characters.indexOf("x") != nil { }` (as `find` was renamed to `indexOf` and is now a protocol extension on `CollectionType`, while `String` no longer is and instead has a `characters` collection property) – Airspeed Velocity Jun 23 '15 at 15:46
  • Now in Swift 4 it is: s.index(of: "x") != nil – CodenameDuchess Dec 31 '17 at 22:06
0

Here you go:

if emailString.rangeOfString("@") != nil{
    println("@ exists")
}
Daniel
  • 20,420
  • 10
  • 92
  • 149
0

You can use this

if emailString.rangeOfString("@") == nil {
        println("Email must contain at sign.")
}
saurabh
  • 6,687
  • 7
  • 42
  • 63