Check if the string contains a number greater 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 greater than 80. I do not need to know where, how much or what is the actual number, but just a logical value (YES or NO). I was thinking of regexing the string to remove everything except numbers, but after that I am not sure which efficient way to do the validation.

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

Thanks!

+6
source share
1 answer

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; 
+3
source

Source: https://habr.com/ru/post/948822/


All Articles