0

I have a NSString formatted like this:

"Hello world 12 looking for some 56"

I want to find all instances of numbers separated by whitespace and place them in an NSArray. I dont want to remove the numbers though.

Whats the best way of achieving this?

René Vogt
  • 43,056
  • 14
  • 77
  • 99
rndy
  • 107
  • 1
  • 6

3 Answers3

2

This is a solution using regular expression as suggested in the comment.

NSString *string = @"Hello world 12 looking for some 56";

NSRegularExpression *expression = [NSRegularExpression regularExpressionWithPattern:@"\\b\\d+" options:nil error:nil];
NSArray *matches = [expression matchesInString:string options:nil range:(NSMakeRange(0, string.length))];
NSMutableArray *result = [[NSMutableArray alloc] init];
for (NSTextCheckingResult *match in matches) {
  [result addObject:[string substringWithRange:match.range]];
}
NSLog(@"%@", result);
vadian
  • 274,689
  • 30
  • 353
  • 361
0

First make an array using NSString's componentsSeparatedByString method and take reference to this SO question. Then iterate the array and refer to this SO question to check if an array element is number: Checking if NSString is Integer.

Community
  • 1
  • 1
chubao
  • 5,871
  • 6
  • 39
  • 64
  • Im currently using NSArray *a = [self.textparagraph componentsSeparatedByCharactersInSet:[NSCharacterSet decimalDigitCharacterSet]]; which splits via the number, Basically the numbers in the text delineate delay length for AVSpeechSynth. Each number encountered is also treated as a new line so I can insert pauses . This works fine but I need to know the number values that its discarding. – rndy Jan 24 '16 at 15:28
0

I don't know where you are looking to do perform this action because it may not be fast (such as if it's being called in a table cell it may be choppy) based upon the string size.

Code:

+ (NSArray *)getNumbersFromString:(NSString *)str {
    NSMutableArray *retVal = [NSMutableArray array];
    NSCharacterSet *numericSet = [NSCharacterSet decimalDigitCharacterSet];
    NSString *placeholder = @"";
    unichar currentChar;
    for (int i = [str length] - 1; i >= 0; i--) {
        currentChar = [str characterAtIndex:i];
        if ([numericSet characterIsMember:currentChar]) {
            placeholder = [placeholder stringByAppendingString: 
                                [NSString stringWithCharacters:&currentChar 
                                                        length:[placeholder length]+1];
        } else {
            if ([placeholder length] > 0) [retVal addObject:[placeholder intValue]];
            else placeholder = @"";

    return [retVal copy];
}

To explain what is happening above, essentially I am,

  • going through every character until I find a number
  • adding that number including any numbers after to a string
  • once it finds a number it adds it to an array

Hope this helps please ask for clarification if needed

Jab
  • 26,853
  • 21
  • 75
  • 114