首页 > 代码库 > iOS判断字母、数字串

iOS判断字母、数字串

以下为NSString类的扩展方法,分别是判断字符串是否只是包含字母、是否只包含数字、是否只包含字母和数字:

//字母
- (BOOL)cdm_isOnlyLetters {
    NSCharacterSet *letterCharacterset = [[NSCharacterSet letterCharacterSet] invertedSet];
    return ([self rangeOfCharacterFromSet:letterCharacterset].location == NSNotFound);
}
//数字
- (BOOL)cdm_isOnlyNumbers {
    NSCharacterSet *numSet = [[NSCharacterSet characterSetWithCharactersInString:@"0123456789"] invertedSet];
    return ([self rangeOfCharacterFromSet:numSet].location == NSNotFound);
}
//字母和数字
- (BOOL)cdm_isOnlyAlphaNumeric {
    NSCharacterSet *numAndLetterCharSet = [[NSCharacterSet alphanumericCharacterSet] invertedSet];
    return ([self rangeOfCharacterFromSet:numAndLetterCharSet].location == NSNotFound);
}

 

效果展示:

技术分享

 

iOS判断字母、数字串