Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to parse strings in Objective C

Can someone help me to extract int timestamp value from this string "/Date(1242597600000)/" in Objective C

I would like to get 1242597600000.

Thx

like image 374
Mladen Avatar asked Jun 02 '09 09:06

Mladen


People also ask

How to split a string in objective c?

Objective-C Language NSString Splitting If you need to split on a set of several different delimiters, use -[NSString componentsSeparatedByCharactersInSet:] . If you need to break a string into its individual characters, loop over the length of the string and convert each character into a new string.

What is string parsing?

String Parsing "Parsing" is the process of taking a string from a file or the network or the user, and processing it to extract the information we want. A common strategy is to use a few calls to indexOf() to figure out the index numbers of something interesting inside the string.

What is NSString?

A static, plain-text Unicode string object that bridges to String ; use NSString when you need reference semantics or other Foundation-specific behavior.

What is string parsing in Python?

String parsing is the process of dividing the string into tokens using delimiters to extract the desired information. This tutorial is about How to parse a string in python. We will learn how to parse the data strings into a list to extract our desired information using different methods and functions.


2 Answers

One simple method:

NSString *timestampString = @"\/Date(1242597600000)\/";
NSArray *components = [timestampString componentsSeparatedByString:@"("];
NSString *afterOpenBracket = [components objectAtIndex:1];
components = [afterOpenBracket componentsSeparatedByString:@")"];
NSString *numberString = [components objectAtIndex:0];
long timeStamp = [numberString longValue];

Alternatively if you know the string will always be the same length and format, you could use:

NSString *numberString = [timestampString substringWithRange:NSMakeRange(7,13)];

And another method:

NSRange openBracket = [timestampString rangeOfString:@"("];
NSRange closeBracket = [timestampString rangeOfString:@")"];
NSRange numberRange = NSMakeRange(openBracket.location + 1, closeBracket.location - openBracket.location - 1);
NSString *numberString = [timestampString substringWithRange:numberRange];
like image 185
Tom Jefferys Avatar answered Oct 01 '22 13:10

Tom Jefferys


There's more than one way to do it. Here's a suggestion using an NSScanner;

NSString *dateString = @"\/Date(1242597600000)\/";
NSScanner *dateScanner = [NSScanner scannerWithString:dateString];
NSInteger timestamp;

if (!([dateScanner scanInteger:&timestamp])) {
    // scanInteger returns NO if the extraction is unsuccessful
    NSLog(@"Unable to extract string");
}

// If no error, then timestamp now contains the extracted numbers.
like image 23
Abizern Avatar answered Oct 01 '22 13:10

Abizern