Menu
Coddy logo textTech

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 icon

Challenge

Beginner

Read two lines of input. Treat them both as strings to compare case-insensitively, ignoring surrounding whitespace. Print:

  1. match when the cleaned and lower-cased versions are equal, otherwise differ
  2. 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 WORLD

Cheat 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 \n

Try it yourself

let a = readLine()!
let b = readLine()!

// TODO: trim + lowercase to compare; print match/differ then trimmed-uppercased a
quiz iconTest yourself

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

All lessons in Logic & Flow