← Back to Swift Course | Chapter 14: Standard Library & Best Practices | Lesson 1 of 7

String Manipulation

String manipulation means slicing, searching, and reshaping text, like cutting a sentence into words or replacing letters.

Splitting a String

.split(separator:) breaks a string into pieces around a given separator character, returning an array of substrings.

Example: Splitting a String

markup
let sentence = "Swift is fun to learn"
let words = sentence.split(separator: " ")
print(words)
print("Word count: \(words.count)")

Replacing Substrings

.replacingOccurrences(of:with:) returns a new string with every match of the target substring replaced by another.

Example: Replacing Substrings

markup
import Foundation
let text = "I like cats and cats like me"
let replaced = text.replacingOccurrences(of: "cats", with: "dogs")
print(replaced)

Trimming Whitespace

.trimmingCharacters(in: .whitespacesAndNewlines) removes leading and trailing whitespace, which is common when cleaning up user input.

Example: Trimming Whitespace

markup
import Foundation
let messy = "   hello swift   "
let trimmed = messy.trimmingCharacters(in: .whitespacesAndNewlines)
print("[\(trimmed)]")
Common Mistakes
  1. Forgetting .split(separator:) returns an array of Substring, not String, which can matter for some APIs expecting a full String.
  2. Trying to use plain integer slicing on a string instead of the String.Index-based APIs or convenience methods like .prefix() and .suffix().
  3. Using .replacingOccurrences(of:with:) and forgetting it returns a new string rather than modifying the original in place.
Chapter Summary
  • .split(separator:) breaks a string into an array of substrings.
  • .replacingOccurrences(of:with:) returns a new string with matches replaced.
  • .prefix(n) and .suffix(n) return the first or last n characters safely.
  • .trimmingCharacters(in:) removes unwanted characters, commonly whitespace, from the ends of a string.
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.