2

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
Cœur
  • 37,241
  • 25
  • 195
  • 267
LMaker
  • 1,444
  • 3
  • 25
  • 38

3 Answers3

5
  • Find the position of the last dot.
  • Remove all dots preceding this position.

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
Martin R
  • 529,903
  • 94
  • 1,240
  • 1,382
3

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: ""))
Fangming
  • 24,551
  • 6
  • 100
  • 90
1

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"
wottle
  • 13,095
  • 4
  • 27
  • 68