7

I have the following NSString:

NSString *testString=@"megaUser 35 youLost 85 noob 10 showTime 36 pwn 110"

I want to know if this string contains a number larger than 80. I do not need to know where, how many or what the actual number is but simply a boolean value (YES or NO). I have thought about regexing the string to remove everything but numbers from it, but after that I am not sure what an efficient way to do the check would be.

In other words, is there a solution that doesnt require breaking the string into array components and then do one at a time check? If anyone knows how this could be done, please let me know!

Thank you!

Teddy13
  • 3,824
  • 11
  • 42
  • 69

1 Answers1

3

You can use a scanner for this:

// The string to parse
NSString *testString=@"megaUser 35 youLost 85 noob 10 showTime 36 pwn 110";

// Create a new scanner for this string and tell it to skip everything but numbers
NSScanner *scanner = [[NSScanner alloc] initWithString:testString];
NSCharacterSet *nonNumbers = [[NSCharacterSet decimalDigitCharacterSet] invertedSet];
[scanner setCharactersToBeSkipped:nonNumbers];

// Scan integers until we get to the end of the string
// If you will have numbers larger than int, you can use long long and scanLongLong for larger numbers
int largestNumber = 0, currentNumber = 0;
while ([scanner scanInt:&currentNumber] == YES)
{
    if (currentNumber > largestNumber)
        largestNumber = currentNumber;
}

// See if the number is larger than 80
if (largestNumber > 80)
    return YES;

// Nope
return NO;
lnafziger
  • 25,760
  • 8
  • 60
  • 101
  • 1
    Thanks for the quick reply. I will give it a try. Can you tell me if this is resource heavy? Thanks again! – Teddy13 Jul 05 '13 at 23:40
  • It is probably about as fast as you are going to get without parsing the C string, and even then you probably won't gain a lot. If you are doing 10's of thousands of these, then it would be worth profiling different methods to see what is fastest, but otherwise this will be one of the better ways to do it. – lnafziger Jul 05 '13 at 23:43
  • 1
    [This answer](http://stackoverflow.com/a/13355703/937822) of mine shows some different ways to parse a string and the relative speeds of them (they won't all be directly applicable, but you will get a rough idea of different approaches and how fast they are). – lnafziger Jul 05 '13 at 23:47