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")) // truecontains 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
EasyRead a single line of input. Validate it as a simple email by checking all of these:
- It contains exactly one
@(usefilter+counton 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 endAll 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]
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Logic & Flow
1Strings In Depth
Count and IndicesCase and TrimSearching in StringsSplitting and JoiningReplacing SubstringsRecap - Username Check