Swift: Replacing Characters in a String — Complete Guide for Beginners

Online Python Trainer for Beginners

Learn Python easily without overwhelming theory. Solve practical tasks with automatic checking, get hints in Russian, and write code directly in your browser — no installation required.

Start Course

Swift: How to Replace Characters in a String? Complete Guide for Beginners

\n\n

Sooner or later, every Swift developer faces the task: you need to replace some characters in a string with others. It seems simple, right? But beginners often get confused because Swift String is not an array of characters like in C, but a complex Unicode-compatible structure. In this article, we'll cover the most popular and efficient ways to replace characters in Swift, from simple to advanced.

\n\n

We won't just dryly list methods. Instead, we'll break down real examples you'll encounter in the wild: from replacing spaces to removing punctuation and working with emojis. Let's go!

\n\n

Why is Swift String Not Just an Array of Characters?

\n

Before replacing characters, it's important to understand how a string works in Swift. String is a collection of Character, but each Character can consist of multiple Unicode scalars (e.g., the emoji 🚀 or the letter "é" with diacritics). Therefore, indexing by Int doesn't work directly here. Instead, Swift uses String.Index.

\n\n

But for replacing characters, you don't need to dive into the intricacies of indices — there are ready-made high-level methods. Let's look at the most popular ones.

\n\n

Method #1: replacingOccurrences — The King of Replacement

\n

The simplest and most obvious way is to use the replacingOccurrences(of:with:) method. It returns a new string with the occurrences replaced. The original string remains unchanged (Swift is a language with immutable strings by default).

\n\n
let original = "Hello, World!"\nlet replaced = original.replacingOccurrences(of: "World", with: "Swift")\nprint(replaced) // "Hello, Swift!"\nprint(original) // "Hello, World!" — original unchanged
\n\n

This method is ideal for simple cases: replacing a single word, character, or substring. But what if you need to replace several different characters? For example, remove all spaces and periods?

\n\n

Chaining Calls for Multiple Replacements

\n

You can call replacingOccurrences multiple times in a row:

\n\n
let text = "Hello, World! How are you?"\nlet cleaned = text\n    .replacingOccurrences(of: ",", with: "")\n    .replacingOccurrences(of: "!", with: "")\n    .replacingOccurrences(of: " ", with: "_")\nprint(cleaned) // "Hello_World_How_are_you?"
\n\n

Downside: if there are many replacements, the code becomes cumbersome. For such cases, other methods or regular expressions are better suited.

\n\n

Method #2: Replacement Using map and filter (Functional Approach)

\n

Swift is not only OOP but also functional programming. You can iterate over each character of a string using map and replace them based on a condition. This is especially convenient when you need to replace all occurrences of a specific set of characters.

\n\n
let input = "a1b2c3d4"\nlet result = input.map { char -> Character in\n    if char.isNumber {\n        return "X"\n    } else {\n        return char\n    }\n}\nprint(String(result)) // "aXbXcXdX"
\n\n

Here we replaced all digits with "X". And if you need to remove characters? Use filter:

\n\n
let withPunctuation = "Hello!!! How are you??"\nlet noPunctuation = withPunctuation.filter { !$0.isPunctuation }\nprint(noPunctuation) // "Hello How are you"
\n\n

This approach is very flexible: you can use any checks — isNumber, isLetter, isWhitespace, or even comparison with a set of characters.

\n\n

Method #3: Regular Expressions (NSRegularExpression)

\n

When the task becomes more complex (pattern-based replacement, removing all emails, replacing dates), regular expressions are indispensable. Swift supports NSRegularExpression from Foundation.

\n\n
import Foundation\n\nlet text = "My email is test@example.com and yours is user@test.org"\nlet regex = try! NSRegularExpression                

Blogs

Book Recommendations