I have an iphone application in which I want to check whether a string value is from 0 to 9. If it is like that, I want to do something else. Does anybody know how to do this?
Asked
Active
Viewed 334 times
1
-
0 to 9 means its length or the character should be b/w 0 to 9 ? – TheTiger Aug 10 '12 at 12:14
-
I think that could help you: http://stackoverflow.com/questions/1320295/iphone-how-to-check-that-a-string-is-numeric-only – SeToY Aug 10 '12 at 12:16
-
What about localisation - what if you want to match the arabic numerals for example (which are ٠,١,٢,٣,٤,٥,٦,٧,٨,٩ (thanks, wikipedia!) .If you want to be language agnostic, you might want to change your accepted answer to the regular expression. – deanWombourne Aug 10 '12 at 12:59
-
no i was accepted because that was exactly wat i want..and has a beautifull explanation... – hacker Aug 10 '12 at 13:33
3 Answers
6
if (string.length == 1 && [string characterAtIndex:0] >= '0' && [string characterAtIndex:0] <= '9') {
// do something
}
This checks for the string being exactly 1 character long and that character being either 0, 1, 2, 3, 4, 5, 6, 7, 8 or 9.
-
You missed '0'. Change the '1' to a '0' and you'll get every number you wanted. The reason the order works '0' to '9' is that these characters map to ASCII which was included in Unicode for the < 128 case. – David H Aug 10 '12 at 12:35
-
1excellent answer.....great job..everybody should have to demonstrate this when answering the stackoverflow questions. – hacker Aug 10 '12 at 12:38
1
NSString *Number = @"0";
NSString *Regex = @"[0-9]";
NSPredicate *test = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", Regex];
BOOL matches = [test evaluateWithObject:Number];
NSLog(@"Status %d",matches);

Rams
- 1,721
- 12
- 22
0
NSString *st=@"9"; // given number
double val=[st doubleValue];
int i=0;
while(i==val)
{
if(i==val)
{
NSLog(@"NUmber between 0 asnd 9");
break;
}
else
{
i++;
}
}

Vineesh TP
- 7,755
- 12
- 66
- 130