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)
}
}
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
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With