Objective-C Check for Unallowed Characters in String
开发者_Go百科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
NSCharacterSet
s 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
精彩评论