Пошук та заміна тексту

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 (Дивіться також):