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,000
  • 34
  • 174
  • 243
ma11hew28
  • 113,928
  • 113
  • 437
  • 631
  • 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,095
  • 16
  • 27
Sergey Kalinichenko
  • 697,062
  • 78
  • 1,055
  • 1,465
  • 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
  • 19,081
  • 10
  • 86
  • 147
0

You can use this

if emailString.rangeOfString("@") == nil {
        println("Email must contain at sign.")
}
saurabh
  • 6,543
  • 7
  • 40
  • 60