How to extract a numeric value from a string?

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

my name is shishir and my number is 98890876478

Is it possible to extract from 98890876478the specified string?

Or if my line is:

my name is shishir and my number is XXX98890876478XXX

In this state, I can retrieve "98890876478", which is between XXX.

Can this be done?

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

Edit:

Here is 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 return is two, because size == 2. I need to get the value between "XXX".

+3
source share
5 answers

THIS WHAT I HAVE FULLY DONE

NSString *newString = [[theXML componentsSeparatedByCharactersInSet: [[NSCharacterSet decimalDigitCharacterSet] invertedSet]] componentsJoinedByString:@""];
----------------------------------------

NSString *newStr = [newString substringWithRange:NSMakeRange(1, [newString length]-1)];
----------------------------------------

.

0

, NSScanner, .

.

int n;
NSScanner * scanner = [[NSScanner alloc] initWithString:@"Your string 1234"];
[scanner scanInt:&n];
+7
+1

:

+ (NSString *)extractNumberFromText:(NSString *)text
{
  NSCharacterSet *nonDigitCharacterSet = [[NSCharacterSet decimalDigitCharacterSet] invertedSet];
  return [[text componentsSeparatedByCharactersInSet:nonDigitCharacterSet] componentsJoinedByString:@""];
}

:

  • @"1234"@"1234"
  • @"001234"@"001234"
  • @"leading text get removed 001234"@"001234"
  • @"001234 trailing text gets removed"@"001234"
  • @"a0b0c1d2e3f4"@"001234"

, !

+1

stringByTrimmingCharactersInSet .

: "abc 10 cd" → 10 ( )

ex: "abc 10 a 1" → "10 a 1" ( )

Using regex seems like a better idea.

iphone sdk - delete all characters except digits 0-9 from the string

EDIT:

Check not the accepted answer, but the one with more than 50 votes

NSString * number = @"(555) 555-555 Office";
NSString * strippedNumber = [number stringByReplacingOccurrencesOfString:@"[^0-9]" withString:@"" options:NSRegularExpressionSearch range:NSMakeRange(0, [number length])];
0
source

Source: https://habr.com/ru/post/1746541/


All Articles