Sscanf Equivalent in Objective-C

前端 未结 2 1919
不思量自难忘°
不思量自难忘° 2021-01-17 22:28

I\'m currently writing a wavefront OBJ loader in Objective-C and I\'m trying to figure out how to parse data from an NSString in a similar manner to the sscanf() function in

相关标签:
2条回答
  • 2021-01-17 23:03

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

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

    Alternatively,

    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];
    

    From a pure ObjC standpoint, NSScanner provides the -scanInteger or -scanFloat methods to pull ints and floats out of a string.

    NSScanner *aScanner = [NSScanner scannerWithString:string];
    [aScanner scanInteger:anInteger];
    
    0 讨论(0)
  • 2021-01-17 23:17

    The NSScanner class can parse numbers in strings, although it can't be used as a drop-in replacement for sscanf.

    Edit: here's one way to use it. You can also put the / into the list of characters to be skipped.

    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++;
    }
    
    0 讨论(0)
提交回复
热议问题