简体   繁体   中英

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:

"2.3333.555.6664438"

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

"2.33335556664438" 

or

"23333555.6664438"

What would be the best way to accomplish this?

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.)

遍历字符串,也可以将其视为字符数组。...设置标志,以便保留小数点之一...当循环遇到一个时更改标志并切换标志... 。所以您的小数点之一是安全的,仍然在字符串中....删除其余的小数点....循环的简单实现,如果没有的话

I ended up using Martin R's solution to create a protocol extension. (Swift 2.3)

var string = "2.3333.555.6664438".removeDuplicateCharacters(".")

extension String {

  func removeDuplicateCharacters(input: String) -> String {
    let string = self
    var trimmedString = ""
    let preGroups = string.componentsSeparatedByString(input)
    if preGroups.count > 1 {
      trimmedString = preGroups[0] + input + preGroups.dropFirst().joinWithSeparator("")
      return trimmedString
    } else {
      return string
    }
  }
}

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM