汇总:
- NSScanner: NSScanner是一个类,用于在字符串中扫描指定的字符,尤其是把它们翻译/转换为数字和别的字符串。可以在创建NSScaner时指定它的string属性,然后scanner会按照你的要求从头到尾地扫描这个字符串的每个字符。
- NSCharacterSet:主要用来判断已知字符串是否包含制定字符集,而不可以用来保存字符串。
1.使用NSScanner来判断
//判断是否为整形:
- (BOOL)isPureInt:(NSString*)string{
NSScanner* scanner = [NSScanner scannerWithString:string];
int val;
return[scan scanInt:&val] && [scan isAtEnd];
}
//判断是否为浮点形:
- (BOOL)isPureFloat:(NSString*)string{
NSScanner* scan = [NSScanner scannerWithString:string];
float val;
return[scan scanFloat:&val] && [scan isAtEnd];
}
if( ![self isPureInt:str1] || ![self isPureFloat:str1]) {
alert.text = @"警告:含非法字符,请输入纯数字!";
return;
}
2.使用NSCharacterSet
-
(NSCharacterSet *)controlCharacterSet; //控制符
-
(NSCharacterSet *)whitespaceCharacterSet; //空格
-
(NSCharacterSet *)whitespaceAndNewlineCharacterSet;//首位空格
-
(NSCharacterSet *)decimalDigitCharacterSet; //十进制数字
-
(NSCharacterSet *)letterCharacterSet; //文字
-
(NSCharacterSet *)lowercaseLetterCharacterSet; //小写字母
-
(NSCharacterSet *)uppercaseLetterCharacterSet; //大写字母
-
(NSCharacterSet *)nonBaseCharacterSet; //非基础
-
(NSCharacterSet *)alphanumericCharacterSet; //字母数字
-
(NSCharacterSet *)decomposableCharacterSet; //可分解
-
(NSCharacterSet *)illegalCharacterSet; //非法
-
(NSCharacterSet *)punctuationCharacterSet; //标点
-
(NSCharacterSet *)capitalizedLetterCharacterSet; //大写
-
(NSCharacterSet *)symbolCharacterSet; //符号
-
(NSCharacterSet *)newlineCharacterSet NS_AVAILABLE(10_5, 2_0);//换行符
//判断是否是纯字母
- (BOOL)isPureCharacters:(NSString *)string{
string = [string stringByTrimmingCharactersInSet:[NSCharacterSet letterCharacterSet]];
if(string.length > 0) {
return NO;
}
return YES;
}
//判断是否是纯数字
- (BOOL)isPureNum:(NSString *)string{
string = [string stringByTrimmingCharactersInSet:[NSCharacterSet decimalDigitCharacterSet]];
if(string.length > 0) {
return NO;
}
return YES;
}
//判断是否包含连续的数组或字母,yes为包含
- (BOOL)rangeString:(NSString *)string {
BOOL result = NO;
for (int i = 0; i < string.length; i++) {
if (string.length - i < 4 ) {
break;
}
NSString *newStr = [string substringWithRange:NSMakeRange(i, 4)];
if ([self isPureCharacters:newStr] || [self isPureNum:newStr]) {
NSLog(@"%@",newStr);
result = YES; break;
}
}
return result;
}
- (BOOL)isPureCharacters:(NSString *)string{
网友评论