swiftstring

Case-sensitive character replacement in a Swift string


I need to replace characters in a Swift string case-sensitively.

I've been using the replacingOccurrences(of:with:options:range:) built-in string function to change every "a" to a "/a/", every "b" to a "/b/", and so on, like this:

stringConverted = stringConverted.replacingOccurrences(of: "a", with: "/a/", options: [])

Then I change every "/a/" to its corresponding letter, which is "a". I change every "/b/" to its corresponding letter, which is "q", and so on.

My problem is that I need this replacement to be case-sensitive. I've looked this up, but I've tried what I found and it didn't help.

Do I need to use the range argument? Or am I doing something else wrong?


Solution

  • As @Orkhan mentioned you can pass options: .caseInsensitive like below

    let a = "a"
    let start = a.index(a.startIndex, offsetBy: 0)
    let end = a.index(a.startIndex, offsetBy: a.count)
    let range = start..<end
    let value = a.replacingOccurrences(of: "a", with: "/a", options: .caseInsensitive, range: range)
    print(value)