String.replacingOccurrences() / trimmingCharacters()
In Swift, you can replace substrings using replacingOccurrences(of:with:), remove leading and trailing whitespace with trimmingCharacters(in:), and split a string into parts using components(separatedBy:).
Syntax
// Replace substrings
string.replacingOccurrences(of: "search", with: "replacement")
// Replace with options
string.replacingOccurrences(of: "search", with: "replacement",
options: .caseInsensitive)
// Remove leading and trailing characters
string.trimmingCharacters(in: .whitespaces)
string.trimmingCharacters(in: .whitespacesAndNewlines)
// Split by a separator
string.components(separatedBy: "separator")
Method List
| Method | Description |
|---|---|
| string.replacingOccurrences(of: with:) | Returns a new string with all matching substrings replaced. |
| string.replacingOccurrences(of: with: options:) | Replaces matches using options such as case-insensitive or regular expression matching. |
| string.trimmingCharacters(in:) | Removes characters in the specified character set from both ends of the string. |
| string.components(separatedBy:) | Splits the string by a separator string and returns the result as an array. |
| string.components(separatedBy: CharacterSet) | Splits the string by a character set such as whitespace or newline characters. |
| CharacterSet.whitespaces | A character set containing spaces and tabs. |
| CharacterSet.whitespacesAndNewlines | A character set containing whitespace and newline characters. |
Sample Code
import Foundation
// replacingOccurrences: basic replacement
let text = "Hello, World! Hello, Swift!"
let replaced = text.replacingOccurrences(of: "Hello", with: "Hi")
print(replaced) // Hi, World! Hi, Swift!
// Case-insensitive replacement
let html = "<p>Swift is<BR>simple<br></p>"
let cleaned = html.replacingOccurrences(of: "<br>", with: "\n",
options: .caseInsensitive)
print(cleaned)
// trimmingCharacters: remove leading and trailing spaces
let padded = " lots of spaces "
print(padded.trimmingCharacters(in: .whitespaces)) // lots of spaces
// Also remove newlines
let withNewlines = "\n\ntext\n\n"
print(withNewlines.trimmingCharacters(in: .whitespacesAndNewlines)) // text
// components: split a string
let csv = "name,age,city"
let fields = csv.components(separatedBy: ",")
print(fields) // ["name", "age", "city"]
// Split by multiple separators
let messy = "apple;banana,cherry:grape"
let fruits = messy.components(separatedBy: CharacterSet(charactersIn: ";,:"))
print(fruits) // ["apple", "banana", "cherry", "grape"]
// Practical example: strip HTML tags
let inputHTML = "<b>bold</b> and <i>italic</i>"
// Simple version (accurate HTML stripping requires regular expressions)
var stripped = inputHTML
["<b>", "</b>", "<i>", "</i>"].forEach { tag in
stripped = stripped.replacingOccurrences(of: tag, with: "")
}
print(stripped) // bold and italic
Notes
replacingOccurrences(of:with:) replaces all matching occurrences. To replace only a specific range, use range(of:) to get the range first, then apply replaceSubrange(_:with:).
trimmingCharacters(in:) only affects characters at the beginning and end of the string. To remove characters from the middle, use replacingOccurrences. Foundation methods such as replacingOccurrences require import Foundation.
For splitting and joining strings, see String.split() / joined() / String Indices.
If you find any errors or copyright issues, please contact us.