Scan string using nsscanner class

I want to scan this line

"hello I am emp 1313 object of string class 123" 

therefore, in this I want to know if there is any integer value, and if it is present, I want to display them for this. I use the NSScanner class and see the look of my code

 NSString *str = @" hello I am emp 1313 object of string class 123"; NSString *limit = @" object"; NSScanner *scanner = [NSScanner scannerWithString:str]; int i; [scanner scanInt:&i]; NSString *output; [scanner scanUpToString:limit intoString:&output]; NSLog(@"%d",i); 

but the problem is that I cannot do this, and I want to use the NSScanner class, so that you can give me some tips regarding this .....

+4
source share
1 answer

Try:

 NSString *str = @" hello i am emp 1313 object of string class 123"; NSScanner *scanner = [NSScanner scannerWithString:str]; // set it to skip non-numeric characters [scanner setCharactersToBeSkipped:[[NSCharacterSet decimalDigitCharacterSet] invertedSet]]; int i; while ([scanner scanInt:&i]) { NSLog(@"Found int: %d",i); } // reset the scanner to skip numeric characters [scanner setScanLocation:0]; [scanner setCharactersToBeSkipped:[NSCharacterSet decimalDigitCharacterSet]]; NSString *resultString; while ([scanner scanUpToCharactersFromSet:[NSCharacterSet decimalDigitCharacterSet] intoString:&resultString]) { NSLog(@"Found string: %@",resultString); } 

It outputs:

 2010-10-27 14:40:39.137 so[2482:a0f] Found int: 1313 2010-10-27 14:40:39.140 so[2482:a0f] Found int: 123 2010-10-27 14:40:39.141 so[2482:a0f] Found string: hello i am emp 2010-10-27 14:40:39.141 so[2482:a0f] Found string: object of string class 
+11
source

All Articles