String Manipulation
In this page:
import Foundation
string.split(separator: " ")
string.replacingOccurrences(of: "target", with: "replacement")
string.trimmingCharacters(in: .whitespacesAndNewlines)
Splitting a String
.split(separator:) breaks a string into pieces around a given separator character, returning an array of substrings.
Example: Splitting a String
// Declare a constant `sentence`, set to `"Swift is fun to learn"`
let sentence = "Swift is fun to learn"
// Declare a constant `words`, set to `sentence.split(separator: " ")`
let words = sentence.split(separator: " ")
// Print `words` to the console
print(words)
// Print "Word count: \(words.count)" to the console
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 the `Foundation` module
import Foundation
// Declare a constant `text`, set to `"I like cats and cats like me"`
let text = "I like cats and cats like me"
// Declare a constant `replaced`, set to `text.replacingOccurrences(of: "cats", with: "dogs")`
let replaced = text.replacingOccurrences(of: "cats", with: "dogs")
// Print `replaced` to the console
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 the `Foundation` module
import Foundation
// Declare a constant `messy`, set to `" hello swift "`
let messy = " hello swift "
// Declare a constant `trimmed`, set to `messy.trimmingCharacters(in: .whitespacesAndNewlines)`
let trimmed = messy.trimmingCharacters(in: .whitespacesAndNewlines)
// Print "[\(trimmed)]" to the console
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: