0

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?

vikingosegundo
  • 52,040
  • 14
  • 137
  • 178
mrprogrammer
  • 87
  • 2
  • 10

2 Answers2

2

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]);
    }
}
Nate Chandler
  • 4,533
  • 1
  • 23
  • 32
  • This is amazing!!!!!!! I have no idea how it really works but it absolutely works for every instance. Thank you!!!!! Would give an up but only have 12 reputation :( but thank you so much! – mrprogrammer Dec 29 '12 at 03:25
1

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.

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523