-3

I have a case where I need to separate the numeric value and other substring from the main given string.

Suppose the main string is 350.55kph. Then my desired result is 350.55 as a numeric value and kph is other substring.

Can someone help me with this?

Maulik Pandya
  • 2,200
  • 17
  • 26

2 Answers2

1

Here is how:

let string = "350kph"
let stringArray = string.components(separatedBy: CharacterSet.decimalDigits.inverted)
for item in stringArray {
    if let integer = Int(item) {
        print("integer: \(integer)")
    }
}

Note: This would work for strings containing multiple Int eg: "350km per 2hr". You would only require:

let string = "350kph"
let integer = Int(string.components(separatedBy: CharacterSet.decimalDigits.inverted).joined())
print("integer: \(integer)")

Okay I saw your edits, here's how to decimals, (there are other ways too):

let string = "350.55kph"
let components = string.components(separatedBy: ".")
let decimalPart = Int(components.last!.components(separatedBy: CharacterSet.decimalDigits.inverted).joined()) ?? 0
let double = Double("\(components.first ?? "0").\(decimalPart)")
print(decimalPart,"double: \(double)")

Other way: You can modify the CharecterSet to achieve the desired result.

Frankenstein
  • 15,732
  • 4
  • 22
  • 47
1

A regular expression would probably work. Something like ([0-9.]+)([A-Za-z]+) which will extract it into two groups: 1 one with numeric part, the other with the unit.

There's a few options here on how to work with those groups: Swift 3 - How do I extract captured groups in regular expressions?

chedabob
  • 5,835
  • 2
  • 24
  • 44