Case-sensitive String replace operations

Jun 4, 2020 · Follow on Twitter and Mastodon swiftextensions

In this post, we’ll discuss how to replace all occurences of a string within another string. We’ll then create an extension that allows for easier case-sensitive replacements.

The basics

Replacing all occurences of a string within another string is very easy, using the rather long-named replacingOccurrences(of:with:):

let string = "This string contains text"
string.replacingOccurrences(of: "text", with: "characters")
// => "This string contains characters"

However, this will not perform a case-insensitive replacement, which means that

string.replacingOccurrences(of: "Text", with: "characters")
// => "This string contains text"

To allow for case-insensitive contains checks, you can provide a .caseInsensitive option:

string.replacingOccurrences(of: "Text", with: "characters", options: .caseInsensitive)
// => "This string contains characters"

However, I think that the function name is too long and that options is tedious to use.

Extending String

We can create shorter and slightly more convenient extensions to let us perform case-sensitive and case-insensitive replacements:

public extension String {
    
    func replacing(_ string: String, with: String) -> String {
        replacingOccurrences(of: string, with: with)
    }
    
    func replacing(_ string: String, with: String, caseSensitive: Bool) -> String {
        caseSensitive
            ? replacing(string, with: with)
            : replacingOccurrences(of: string, with: with, options: .caseInsensitive)
    }
}

We can now perform case-sensitive and case-insensitive contains checks the same way:

string.replacing("text", with: "characters")
string.replacing("Text", with: "characters", caseSensitive: true)

I like this since it lets me write a little less code when replacing strings in Swift.

Source code

I have added these extensions to my SwiftKit library. You can find the source code here. Feel free to try it out and let me know what you think!

Discussions

Please share any ideas, feedback or comments you may have in the Disqus section below, or by replying on Twitter or Mastodon..

Follow for more

If you found this interesting, follow the Twitter and Mastodon accounts for more content like this, and to be notified when new content is published.