I want to remove all occurrences of char == . in a string except the last one.
E.G:
1.2.3.4
should become:
123.4
Example:
var str = "1.2.3.4"
if let idx = str.range(of: ".", options: .backwards) {
str = str.replacingOccurrences(of: ".", with: "", range: str.startIndex..<idx.lowerBound)
}
print(str) // 123.4
Here is the example code. Split by your character, add that character to the beginning of the last element, and then join them back
let str = "1.2.3.4"
var array = str.components(separatedBy: ".")
if array.count >= 1 {
array[array.count - 1] = "." + array[array.count - 1]
}
print(array.joined(separator: ""))
You could make this easilt reusable as an extension on String.
public extension String {
func stringByReplacingAllButLastOccurrenceOfString(target: String, withString replaceString: String) -> String {
if let idx = self.rangeOfString(target, options: .BackwardsSearch) {
return self.stringByReplacingOccurrencesOfString(target, withString: replaceString, range: self.startIndex..<idx.first!)
}
return self
}
}
Running through a few of the scenarios, you get:
strResult = "1.2.3.4.5".stringByReplacingAllButLastOccurrenceOfString(".", withString: "")
// result "1234.5"
strResult = "1234.5".stringByReplacingAllButLastOccurrenceOfString(".", withString: "")
// result "1234.5"
strResult = "1.23.4.5".stringByReplacingAllButLastOccurrenceOfString(".", withString: "")
// result "1234.5"
strResult = "1234.5".stringByReplacingAllButLastOccurrenceOfString(".", withString: "")
// result "1234.5"
strResult = "12345".stringByReplacingAllButLastOccurrenceOfString(".", withString: "")
// result "12345"