Case and Trim
Part of the Logic & Flow section of Coddy's Swift journey — lesson 2 of 56.
The case methods return new strings, they don't modify the original. Use them on text that comes from the user before comparing it.
let raw = " Hello World "
print(raw.uppercased()) // " HELLO WORLD "
print(raw.lowercased()) // " hello world "To strip leading and trailing whitespace, use trimmingCharacters(in:) from Foundation (already imported on this platform):
let cleaned = raw.trimmingCharacters(in: .whitespaces)
print(cleaned) // "Hello World"
print(cleaned.count) // 11.whitespaces covers spaces and tabs. Use .whitespacesAndNewlines when input might contain a trailing \n.
Challenge
BeginnerRead two lines of input. Treat them both as strings to compare case-insensitively, ignoring surrounding whitespace. Print:
matchwhen the cleaned and lower-cased versions are equal, otherwisediffer- The cleaned (trimmed) version of the first line in upper case
For input Hello World on the first line and HELLO world on the second, the output is:
match
HELLO WORLDCheat sheet
String case methods return new strings (original unchanged):
str.uppercased() // "hello" → "HELLO"
str.lowercased() // "HELLO" → "hello"Strip leading/trailing whitespace with trimmingCharacters(in:):
let cleaned = raw.trimmingCharacters(in: .whitespaces) // spaces & tabs
let cleaned = raw.trimmingCharacters(in: .whitespacesAndNewlines) // includes \nTry it yourself
let a = readLine()!
let b = readLine()!
// TODO: trim + lowercase to compare; print match/differ then trimmed-uppercased a
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