判断字符串是否是纯数字的方法总结

 

判断字符串是否是纯数字的方法总结

//第一种方式是使用NSScanner:
//1. 整形判断
- (BOOL)isPureInt:(NSString *)string{
  NSScanner* scan = [NSScanner scannerWithString:string];
  int val;
  return [scan scanInt:&val] && [scan isAtEnd];
}

//2.浮点形判断:
- (BOOL)isPureFloat:(NSString *)string{
  NSScanner* scan = [NSScanner scannerWithString:string];
  float val;
  return [scan scanFloat:&val] && [scan isAtEnd];
}

//(利用1. 整形判断 2.浮点形判断 )判断是否是纯数字
 +(BOOL)stringIsNumbers:(NSString *)string{

  if( ![Tools isPureInt:string] && ![Tools isPureFloat:string])
  {

  return NO;

  }else {

  return YES;
  }

}

//第二种方式是使用循环判断
- (BOOL)isPureNumandCharacters:(NSString *)text
{
  for(int i = 0; i < [text length]; ++i) {
  int a = [text characterAtIndex:i];
  if ([self isNum:a]){
  continue;
  } else {
  return NO;
  }
  }
  return YES;
}

//C语言中常用的方式.
- (BOOL)isAllNum:(NSString *)string{
  unichar c;
  for (int i=0; i<string.length; i++) {
  c=[string characterAtIndex:i];
  if (!isdigit(c)) {
  return NO;
  }
  }
  return YES;
}

//第三种方式则是使用NSString的trimming方法
- (BOOL)isPureNumandCharacters:(NSString *)string
{
  string = [string stringByTrimmingCharactersInSet;[NSCharacterSet decimalDigitCharacterSet]];
  if(string.length > 0)
  {
  return NO;
  }
  return YES;
}

//用正则表达式判断
- (BOOL) deptNumInputShouldNumber:(NSString *)str
{
  NSString *regex = @"[0-9]*";
  NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",regex];
  if ([pred evaluateWithObject:str]) {
  return YES;
  }
  return NO;
}

 

posted @ 2017-02-27 18:44  #零下一度&  阅读(4018)  评论(0编辑  收藏  举报