Wednesday, March 16, 2011

Determine if string is numeric only

 In Objective-C there is no in-built method which determines whether the given string is numeric only or is an alphanumeric, but has provided ways to do that.


The objective can be achieved using the NSCharacterSet class, which provides a set of characters.
Using below method we can identify the whether the string is numeric or alphanumeric.


- (void)testNumeric{
      NSString *result=@"2011";
      if([self isNumeric:result]){
// Numeric
        }else{
  // Alphanumeric
        }
}
- (BOOL)isNumeric:(NSString*)inputString{
        BOOL isValid=NO;
       NSCharacterSet *alphaNumbersSet = [NSCharacterSet decimalDigitCharacterSet];
       NSCharacterSet *stringSet = [NSCharacterSet characterSetWithCharactersInString:inputString];
       isValid = [alphaNumbersSet isSupersetOfSet:stringSet];
       return isValid;
}


decimalDigitCharacterSet is a character set containing the characters in the category of Decimal Numbers,i.e, the set with all numeric characters.


Method characterSetWithCharactersInString: returns the character set containing the characters in the given string, i.e, the set with characters '2','0','1','1' in our case.


Using the two sets, we determine whether all characters of inputString is contained in alphaNumbersSet.


Happy coding.

2 comments:

  1. I think your isNumeric: method needs to have (BOOL) as the return type.

    ReplyDelete
  2. Hi Peter, Thanks for pointing it out.

    ReplyDelete