I have a string "Number: 0.3456"
How can I remove the "Number: " part to extract the double value "0.3456" from it using NSRange
?
Asked
Active
Viewed 381 times
0

Gabriele Petronella
- 106,943
- 21
- 217
- 235

K Hsueh
- 610
- 1
- 10
- 19
3 Answers
1
If Number: X.XXX
is a fixed pattern you simply can do something like
NSString * string = @"Number: 0.3456";
NSString * prefix = @"Number: ";
NSString * doubleString = [string substringFromIndex:prefix.length];
double yourDouble = [doubleString doubleValue];
if you really want to use NSRange
you could do something like
NSString * string = @"Number: 0.3456";
NSString * substringToRemove = @"Number: ";
NSRange substringRange = [string rangeOfString:substringToRemove];
NSString * doubleString = [string stringByReplacingCharactersInRange:substringRange
withString:@""];
double yourDouble = [doubleString doubleValue];
The main difference is that the second example will remove every occurrence of the Number:
string from the original one, whereas the first will just remove the prefix.

Gabriele Petronella
- 106,943
- 21
- 217
- 235
-
my bad, I forgot that `NSRange` is a plain C struct. Thank you for pointing it out – Gabriele Petronella Jan 23 '13 at 23:42
0
You can use an NSScanner, as long as you set the scan location first:
double result;
NSString *str = @"Number: 0.3456";
NSScanner *scanner = [NSScanner scannerWithString:str];
[scanner setScanLocation:[@"Number: " length]];
[scanner scanDouble:&result];
Remember that scanDouble:
returns YES
or NO
to indicate whether a scan was successful or not.

dreamlax
- 93,976
- 29
- 161
- 209