如何确保字符串仅包含a-z和A-Z字符?

时间:2011-01-29 15:21:07

标签: iphone objective-c

我输入的用户名只需要输入a-z和A-Z。我想验证这个名字,请帮助我。

提前致谢

2 个答案:

答案 0 :(得分:4)

NSCharacterSet *nonAlphabetChars = [[NSCharacterSet characterSetWithCharactersInString:@"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"] invertedSet];
if ([myString rangeOfCharacterFromSet:nonAlphabetChars].location == NSNotFound) {
    // myString is valid
    ...
} else {
    // myString contains at least one invalid character
    ...
}

答案 1 :(得分:1)

你可以这样做:

NSCharacterSet *allowed = [NSCharacterSet alphanumericCharacterSet];
NSCharacterSet *forbidden = [allowed invertedSet];
NSRange range = [string rangeOfCharacterFromSet:forbidden];
BOOL isValid = (range.location == NSNotFound);

alphanumericCharacterSet可能不完全符合您的要求,有关更多选项,请参阅NSCharacterSet