DJSK DJSK - 1 year ago 130
Swift Question

Replace all but one occurrence of a character in a string

I have a string of numbers that may contain more than one decimal point because of user error. Something like:


I want to be able to remove all but one of the decimal points in the string (either the first or the last preferably):




What would be the best way to accomplish this?

Answer Source

Split into groups separated by the period character, and concatenate all but the first group. Example (Swift 3):

var string = "2.3333.555.6664438"
let groups = string.components(separatedBy: ".")
if groups.count > 1 {
    string = groups[0] + "." + groups.dropFirst().joined()
print(string) // 2.33335556664438

Or: Find the first period character and remove all subsequent occurrences:

var string = "2.3333.555.6664438"
if let r = string.range(of: ".") {
    string = string.substring(to: r.upperBound)
        + string.substring(from: r.upperBound).replacingOccurrences(of: ".", with: "")

print(string) // 2.33335556664438

(But note that the decimal separator is locale dependent and not necessarily the period character. For example, it is a comma in Germany.)

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download