Question

I have a script for an application and I'm stuck on a way to extract a specific number For example in:

\n@JulianJear\nApplication Development 4 iPhone and iPad.\n5\n

I haven't been able to come up with a way to remove the "5" without also getting the "4" from that string. I thought of using a scanner but the amount of characters in this piece of text for every user is going to be different. So, what other ways can be used to extract this number?

Was it helpful?

Solution

If the text being parsed always has the following format

<Handle>
<Title>
<Number>

i.e.

\n<Name>\n<Title>\n<Number>\n

You can use an NSScanner to parse the string:

#import <Foundation/Foundation.h>

int main(int argc, char *argv[]) {
    @autoreleasepool 
    {
        NSString *string = @"\n@JulianJear\nApplication Development 4 iPhone and iPad.\n5\n";

        NSScanner *scanner = [[NSScanner alloc] initWithString:string];
        NSCharacterSet *newlineCharacterSet = [NSCharacterSet characterSetWithCharactersInString:@"\n"];

        NSString *handle = nil;
        NSString *title = nil;
        NSString *number = nil;

        [scanner scanUpToCharactersFromSet:newlineCharacterSet intoString:&handle];
        [scanner scanUpToCharactersFromSet:newlineCharacterSet intoString:&title];
        [scanner scanUpToCharactersFromSet:newlineCharacterSet intoString:&number];

        NSLog(@"\nhandle=%@\ntitle=%@\nnumber=%d", handle, title, [number intValue]);
    }
}

OTHER TIPS

You can split the string on \n, and look for strings that represent numbers:

NSArray *tokens = [str componentsSeparatedByCharactersInSet:
      [NSCharacterSet characterSetWithCharactersInString:@"\n"]];

Go through the strings in the tokens array, and take the first string that represents a number.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top