开发者

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


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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜