I am able to extract numbers using below code:
let weightt = x.components(separatedBy: CharacterSet.decimalDigits.inverted).joined(separator: "")
For example, I'm getting "01" from string "0.1kg"
But how to extract "0.1" from string "0.1kg" ?
I am able to extract numbers using below code:
let weightt = x.components(separatedBy: CharacterSet.decimalDigits.inverted).joined(separator: "")
For example, I'm getting "01" from string "0.1kg"
But how to extract "0.1" from string "0.1kg" ?
You can use
Input
let x = "0.1kg"
let weightt = x.components(separatedBy: CharacterSet.init(charactersIn: "0123456789.").inverted).joined(separator: "")
output
0.1
Scanner is the correct solution. While this works for the single case in the original question, there are a huge number of cases where it doesn't work at all (ex. "$1.56")A good approach is to use Scanner.
Example:
let string = " 0.1 kg"
let scanner = Scanner.localizedScanner(with: string)
var weight = 0.0
if scanner.scanDouble(&weight) {
print(weight) // 0.1
}
The scanDouble()/scanFloat() methods parse all kinds of
floating point notations (+12.34, -56.78, 1.23e4, 1,23, etc.),
skip initial whitespace, support multiple locales, and scan as much as possible from the given string.
string is the String variable containing the string to be parsed, here " 0.1 kg". The parse result is stored in the weight variable, which has the type Double.Use
let result = weightt.stringByReplacingOccurrencesOfString("kg", withString: "")
If you want to remove all characters from weightt use code. Means if it is gm instead of kg.
let result = string.stringByReplacingOccurrencesOfString("[^A-Za-z]", withString: "",
options: NSStringCompareOptions.RegularExpressionSearch, range:nil).stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet())
"[^A-Za-z]" to find anything that isn't a letter?You didn't say anything about the constraints of the input, so I assume it is a valid decimal number followed by a unit.
You can use prefix to do this if that's the case:
let weight = "0.1kg"
let result = String(weight.characters.prefix {
"012346789.".characters.contains($0)) })
.description for anything but debug output always feels a bit of a code smell to me (and the exact description format is not guaranteed officially). You can achieve the same with String(weight.characters.prefix { "012346789.".characters.contains($0) })