Teddy13
Teddy13

Reputation: 3854

check if string contains number larger than

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!

Upvotes: 7

Views: 1018

Answers (1)

lnafziger
lnafziger

Reputation: 25740

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;

Upvotes: 3

Related Questions