4

I want to scan this string

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

so in this I want to know if their are any integer value present and if present I want to display them for this I am using the NSScanner class and heres a view 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 am not able to do it and I want to use NSScanner class only so can you experts give me some suggesstions regarding this.....

1 Answer 1

11

Give this a 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 
Sign up to request clarification or add additional context in comments.

3 Comments

and can u also tell me how to find strings only
am trying to do the same by this piece of line [scanner setCharactersToBeSkipped:[[NSCharacterSet alphanumericCharacterSet]invertedSet]];
i've updated the answer to include scanning for strings. invertedSet basically says "all characters except these ones"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.