Ad space (banner)
๐ŸฆSwift Lessons
Lesson 39 / 68

Normalizing Strings (trimmingCharacters, Unifying Case)

In this lesson you will learn how to normalize strings in Swift, so inconsistent formatting can still be compared. This is for anyone searching for "Swift string normalization".

Text entered by a user tends to carry stray leading or trailing spaces and inconsistent capitalisation. Stripping the spaces with .trimmingCharacters(in:) and unifying the case with .lowercased() is called normalization.

The sample code runs str.trimmingCharacters(in: .whitespaces).lowercased() inside a normalize() function, removing surrounding whitespace and then folding to lower case. You can see two strings that look different compare as equal once normalized.

A common stumbling block for beginners is comparing strings without doing this first. Two values that look identical to a human can still come back as false, and the cause is hard to spot.

In real-world development normalization is a basic technique you cannot do without in input validation and login handling.

๐Ÿ“– Reference code
โœ๏ธ Your code
Type your code, then press "Run"

๐Ÿงช This site can't compile or run Swift directly, so it checks on the spot whether what you typed matches the reference code (scoring happens entirely in your browser โ€” nothing is sent anywhere).

Ad space (banner)
Ad space (in-article)