Reputation: 2446
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?
Upvotes: 2
Views: 3114
Reputation: 1865
Try this:
let oldString = "Change This, change this"
let newString = myString.replacingOccurrences(of: "change this", with: "to this", options: .caseInsensitive)
Both work with options: .caseInsensitive
Upvotes: 0
Reputation: 15015
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)
Upvotes: 10