iOS 中文英文字符集

1
+ (NSCharacterSet *) chineseAndEngSet
{
    if (chineseNameSet == nil)
   {
      NSMutableCharacterSet *aCharacterSet = [[NSMutableCharacterSet alloc] init];

      NSRange lcEnglishRange;
      lcEnglishRange.location = (unsigned int)0x4e00;
      lcEnglishRange.length = (unsigned int)0x9fa5 - (unsigned int)0x4e00;
      [aCharacterSet addCharactersInRange:lcEnglishRange];
      [aCharacterSet addCharactersInString:@"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"];
      chineseAndEngSet = aCharacterSet;
    }
  return chineseAndEngSet;
}

中文字符的正则表达式(包含繁体中文) ^[\u4E00-\u9FA5]+$

验证中文

1
- (BOOL)validateInputWithString:(NSString *)aString
{
  NSString * const regularExpression = @"^[\u4E00-\u9FA5]+$";
  NSError *error = NULL;
  NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:regularExpression
                                                                         options:NSRegularExpressionCaseInsensitive
                                                                           error:&error];
  if (error) {
      NSLog(@"error %@", error);
  }

  NSUInteger numberOfMatches = [regex numberOfMatchesInString:aString
                                                      options:0
                                                        range:NSMakeRange(0, [aString length])];
  return numberOfMatches > 0;
}

判断双空格方法

1
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{

//Check for double space
 return !(range.location > 0 &&
        [string length] > 0 &&
        [[NSCharacterSet whitespaceCharacterSet] characterIsMember:[string characterAtIndex:0]] &&
        [[NSCharacterSet whitespaceCharacterSet] characterIsMember:[[textField text] characterAtIndex:range.location - 1]]);

}