views:

32

answers:

1

Hello,

How would I, in objective-c, make it so only strings with a-z characters were allowed? I.E. no & characters, no - characters, etc.

Thanks! Christian Stewart

+3  A: 

NSCharacterSets are going to be the key here. First you'll need the character set of alphabetical characters:

NSCharacterSet* letters = [NSCharacterSet characterSetWithRange:NSMakeRange('a', 26)];

And then, if you want to check if the string contains a character that's not a letter, you can use this set's inverse:

NSCharacterSet* notLetters = [letters invertedSet];

Then use NSString's rangeOfCharacterFromSet: with notLetters, and if the range doesn't start with NSNotFound, there are forbidden characters in your string.

NSRange badCharacterRange = [myString rangeOfCharacterFromSet:notLetters];
if (badCharacterRange.location != NSNotFound) // found bad characters
zneak
Arr; beat me while I was typing.
Wevah