Determine if NSString is the first character number

I just wanted to know how I can determine if the first NSS character is a number.

+6
objective-c numbers iphone xcode nsstring
source share
5 answers
BOOL hasLeadingNumberInString(NSString* s) { if (s) return [s length] && isnumber([s characterAtIndex:0]); else return NO; 

}

If you process several NSStrings at once (for example, loop through an array), and you want to check each of them for formatting, for example, leading numbers, it is better to enable checks so that you do not try to evaluate an empty or nonexistent string.

Example:

 NSString* s = nil; //Edit: s needs to be initialized, at the very least, to nil. hasLeadingNumberInString(s); //returns NO hasLeadingNumberInString(@""); //returns NO hasLeadingNumberInString(@"0123abc"); //returns YES 
+20
source share

Yes. You can do:

 NSString *s = ...; // a string unichar c = [s characterAtIndex:0]; if (c >= '0' && c <= '9') { // you have a number! } 
+8
source share

I can come up with two ways to do this. you can use

 [string rangeOfCharacterFromSet:[NSCharacterSet decimalDigitCharacterSet]].location == 0 

Or you can use

 [[NSCharacterSet decimalDigitCharacterSet] characterIsMember:[string characterAtIndex:0]] 
+7
source share

Check the return value:

 [myString rangeOfCharacterFromSet:[NSCharacterSet decimalDigitCharacterSet]]; 

If the location value of the returned range is 0 , you must match the first character.

+5
source share

Instead of using a call that scans the entire line, it is best to pull out the first char and then see what it is:

 char test = [myString characterAtIndex:0]; if (test >= '0' && test <= '9') return YES else return NO 
+4
source share

All Articles