0

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?

Gabriele Petronella
  • 106,943
  • 21
  • 217
  • 235
K Hsueh
  • 610
  • 1
  • 10
  • 19

3 Answers3

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
0

I suggest you use [NSScanner scanDouble:]

pickwick
  • 3,134
  • 22
  • 30
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