Sscanf Equivalent in Objective-C

I am currently writing an OBJ wavefront loader in Objective-C, and I am trying to figure out how to parse data from NSString similarly to the sscanf () function in C.

OBJ files define faces in x, y, z triplets of vertices, texture coordinates and normals, such as:

f 1.43//2.43 1.11//2.33 3.14//0.009 

At the moment, I'm not interested in the texture coordinates. In C, a simple way to parse this line would look like this:

 sscanf(buf, "f %d//%d %d//%d %d//%d", &temp[0], &temp[1], &temp[2], &temp[3], &temp[4], &temp[5]); 

Obviously, NSStrings cannot be used in sscanf () without first converting them to a C-style string, but I wonder if there is a more elegant way to do this without such a conversion.

+8
objective-c cocoa 3d
source share
2 answers

The NSScanner class can parse line numbers, although it cannot be used as a replacement for sscanf replacement.

Edit : here is one way to use it. You can also put the / character in the list of characters to skip.

 float temp[6]; NSString *objContent = @"f 1.43//2.43 1.11//2.33 3.14//0.009"; NSScanner *objScanner = [NSScanner scannerWithString:objContent]; // Skip the first character. [objScanner scanString:@"f " intoString:nil]; // Read the numbers. NSInteger index=0; BOOL parsed=YES; while ((index<6)&&(parsed)) { parsed=[objScanner scanFloat:&temp[index]]; // Skip the slashes. [objScanner scanString:@"//" intoString:nil]; NSLog(@"Parsed %f", temp[index]); index++; } 
+9
source share

To go from NSString to C-String (char *), use

 NSString *str = @"string"; const char *c = [str UTF8String]; 

As an alternative

 NSString *str = @"Some string"; const char *c = [str cStringUsingEncoding:NSUTF8StringEncoding]; 

Provide access to the sscanf () function.

To go the other way, use

 const *char cString = "cStr"; NSString *string = [NSString stringWithUTF8String:cString]; 

Or

 const *char cString = "cStr"; NSString *myNSString = [NSString stringWithCString:cString encoding:NSASCIIStringEncoding]; 

In terms of pure ObjC, NSScanner provides the -scanInteger or -scanFloat for pulling an int and floating out of a string.

 NSScanner *aScanner = [NSScanner scannerWithString:string]; [aScanner scanInteger:anInteger]; 
+5
source share

All Articles