In this post I will show you how to read the integer value from the string, for this create a command line utility project and select foundation tools from it and give your project an appropriate name and save it.
Step 1: create a class and name it scanner with two function one will read the integer value from the string and the other will read only the string value from the string ignoring the integer value. Here's a glimpse at my code
Step 2: Here's how you read a integer value from the string
NSScanner class has a object method called setCharacterToBeSkipped which ignores a character while scanning a string.
-(void) scanInteger
{
NSString *str = @" hello 12 i am emp 1313 object of string class 123";
NSScanner *scanner = [NSScanner scannerWithString:str]; //setting the scanning location,
[scanner setCharactersToBeSkipped:[[NSCharacterSetdecimalDigitCharacterSet]invertedSet]];
int i;
while([scanner scanInt:&i])
{
NSLog(@"%d",i);
}
}
The line
[scanner setCharactersToBeSkipped:[[NSCharacterSet decimalDigitCharacterSet]invertedSet]];
says that the scanner has to get only the integer data and ignore all the other data from the string and then I have applied a loop so that the scanner can scan the entire string and prompt the integer value on the screen.
Reading String and Ignoring integers...
Step 3: Create another function which will read the string data from the string ignoring the integer value for that heres my code
-(void) scanString
{
NSString *str = @"Hello 1234 my name is rahul 5678";
NSScanner *scanner = [NSScanner scannerWithString:str];
NSString *result;
[scanner setCharactersToBeSkipped:[NSCharacterSet decimalDigitCharacterSet]];
while([scanner scanUpToCharactersFromSet:[NSCharacterSet decimalDigitCharacterSet]intoString:&result])
{
NSLog(@"%@",result);
}
}
And finally run the application by importing the scanner.h file into the main.m and creating the object of scanner class
#import <Foundation/Foundation.h>
#import "scanner.h"
int main (int argc, const char * argv[]) {
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
scanner *obj = [[scanner alloc]init];
[obj scanInteger];
[obj scanString];
[pool drain];
return 0;
}
Run the application by pressing Run from the meny bar and select console and then Build and Go.
No comments:
Post a Comment