String Manipulation
In this page:
Splitting a String
.split(separator:) breaks a string into pieces around a given separator character, returning an array of substrings.
Example: Splitting a String
let sentence = "Swift is fun to learn"
let words = sentence.split(separator: " ")
print(words)
print("Word count: \(words.count)")
Login to try C/C++/Java/PHP code in the editor
Replacing Substrings
.replacingOccurrences(of:with:) returns a new string with every match of the target substring replaced by another.
Example: Replacing Substrings
import Foundation
let text = "I like cats and cats like me"
let replaced = text.replacingOccurrences(of: "cats", with: "dogs")
print(replaced)
Login to try C/C++/Java/PHP code in the editor
Trimming Whitespace
.trimmingCharacters(in: .whitespacesAndNewlines) removes leading and trailing whitespace, which is common when cleaning up user input.
Example: Trimming Whitespace
import Foundation
let messy = " hello swift "
let trimmed = messy.trimmingCharacters(in: .whitespacesAndNewlines)
print("[\(trimmed)]")
Login to try C/C++/Java/PHP code in the editor
- Forgetting
.split(separator:)returns an array ofSubstring, notString, which can matter for some APIs expecting a fullString. - Trying to use plain integer slicing on a string instead of the
String.Index-based APIs or convenience methods like.prefix()and.suffix(). - Using
.replacingOccurrences(of:with:)and forgetting it returns a new string rather than modifying the original in place.
.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: