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)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.