Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift String Extension to replace first characters without occurrence

Tags:

string

ios

swift

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)
    }


} 
like image 679
Stranger B. Avatar asked May 29 '26 20:05

Stranger B.


2 Answers

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

like image 57
shannoga Avatar answered Jun 01 '26 20:06

shannoga


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)
like image 33
Kevin Avatar answered Jun 01 '26 20:06

Kevin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!