Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Extract a Numerical Value from a String?

Is it possible to extract a number from a string. For example, I have a string:

my name is shishir and my number is 98890876478

Can I extract on 98890876478 from the above string?

Or if my string is:

my name is shishir and my number is XXX98890876478XXX

In this condition can I extract `98890876478", which is in between of XXX.

Is it possible to do this?

I am getting a message from a server which should be in the format as above, and I need the numeric value for further operations

Edit:

Here's the code I'm trying to use:

NSString *logString = [NSString stringWithFormat:@"%@",theXML]; 
NSString *digits = [logString stringByTrimmingCharactersInSet:[[NSCharacterSet decimalDigitCharacterSet] invertedSet]]; 
NSLog(@"Message id: %i", [digits intValue]);

which outputs:

2010-05-21 16:37:07.092 sms[5311:207] OK: message-ID XXX110103468XXX
2010-05-21 16:37:07.851 sms[5311:207] Message id: 2

I think its returning two because size==2. I need to retrieve the value between the "XXX".

like image 459
Shishir.bobby Avatar asked May 16 '26 04:05

Shishir.bobby


1 Answers

I think what you need is NSScanner, this allows you to take out parts of the string.

e.g.

int n;
NSScanner * scanner = [[NSScanner alloc] initWithString:@"Your string 1234"];
[scanner scanInt:&n];
like image 63
AndersK Avatar answered May 18 '26 19:05

AndersK



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!