3

I'd like to replace a character in my string but only the first occurrence of the character.

I'm using this string extension ! but it's replacing all the occurrences

extension String {

    func replace(target: String, withString: String) -> String
    {
        return self.stringByReplacingOccurrencesOfString(target, withString: withString, options: NSStringCompareOptions.LiteralSearch, range: nil)
    }


} 
shannoga
  • 19,649
  • 20
  • 104
  • 169
Stranger B.
  • 9,004
  • 21
  • 71
  • 108

2 Answers2

5

You have to specify the range, so this way you can find only the first

var str = "Hello, playground"
var strnigToReplace = "l"
var stringToReplaceTO = "d"

if let range =  str.rangeOfString(strnigToReplace) {
    str = str.stringByReplacingOccurrencesOfString(strnigToReplace, withString: stringToReplaceTO, options: NSStringCompareOptions.LiteralSearch, range: range)
}

This will find the first occurrence of the character and will limit the replacement to the range of this string. Hope it helps

shannoga
  • 19,649
  • 20
  • 104
  • 169
1

I implemented this function similar to shannoga but as a mutating extension on String. This way you don't need to create a new copy, you can just modify a var.

extension String {
    mutating func replaceFirstOccurrence(original: String, with newString: String) {
        if let range = self.rangeOfString(original) {
            replaceRange(range, with: newString)
        }
    }
}

Example:

var testString = "original"
testString.replaceFirstOccurrence("o", with: "O")
print(testString)
Kevin
  • 16,696
  • 7
  • 51
  • 68