Swift:
Пошук та заміна тексту
How to: (Як робити:)
let originalText = "Hello, World!"
let searchText = "World"
let replaceText = "Ukraine"
if let range = originalText.range(of: searchText) {
let replacedText = originalText.replacingCharacters(in: range, with: replaceText)
print(replacedText) // Output: Hello, Ukraine!
} else {
print("Search text not found.")
}
Deep Dive (Глибше Занурення)
Back in the day, text operations were cumbersome in programming languages, but Swift made them a breeze. Swift’s String class has rich functionality for search and replace, using methods like range(of:)
and replacingCharacters(in:with:)
. Alternatives? Sure – regular expressions are powerful for complex patterns, and text frameworks provide more features. As for details – Swift’s strings are Unicode-compliant, so search-and-replace works smoothly even with diverse alphabets and emojis.
See Also (Дивіться також):
- Swift’s String documentation: https://developer.apple.com/documentation/swift/string
- Regular Expressions in Swift: https://nshipster.com/swift-regular-expressions/
- Working with Strings in Swift: https://www.hackingwithswift.com/articles/108/how-to-use-strings-in-swift