Menu
Coddy logo textTech

Searching in Strings

Part of the Logic & Flow section of Coddy's Swift journey — lesson 3 of 56.

Three quick checks for whether a substring lives inside another:

let email = "alice@coddy.tech"
print(email.contains("@"))         // true
print(email.hasPrefix("alice"))    // true
print(email.hasSuffix(".tech"))    // true

contains takes any substring, while hasPrefix and hasSuffix only look at the start or the end. They are all case-sensitive, so lowercase the string first if that matters.

Combine these with ! for a quick "missing" test:

if !email.contains("@") {
    print("not a valid email")
}
challenge icon

Challenge

Easy

Read a single line of input. Validate it as a simple email by checking all of these:

  • It contains exactly one @ (use filter + count on the characters)
  • It does not start or end with @
  • It ends with .tech, .com, or .org (case-insensitive)

Print valid when every check passes, otherwise invalid. Compare against the lower-cased version of the input.

For input alice@CODDY.TECH, the output is valid.

Cheat sheet

Check if a string contains a substring, or starts/ends with one:

let email = "alice@coddy.tech"
email.contains("@")        // true – anywhere in the string
email.hasPrefix("alice")   // true – at the start
email.hasSuffix(".tech")   // true – at the end

All three are case-sensitive. Use .lowercased() first if needed:

email.lowercased().hasSuffix(".tech")

Use ! to test for absence:

if !email.contains("@") { print("not a valid email") }

Try it yourself

let line = readLine()!

// TODO: validate exactly-one '@', not at the edges, suffix in [.tech .com .org]
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Logic & Flow