iOS 判斷字符串是否是純中文字符以及字符串的范圍 – iPhone手機開發 iPhone軟體開發教學課程

判斷一個字符串是否是純中文字符,代碼如下

 

+ (BOOL)isChinese:(NSString *)userName
{
    NSString *match = @"(^[\u4e00-\u9fa5]+$)";
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF matches %@", match];
    return [predicate evaluateWithObject:userName];
}

 

判斷一個字符串是否在某個范圍 比如2~15個漢字,代碼如下

 

 

+ (BOOL)isValidateName:(NSString *)name{
    NSUInteger  character = 0;
    for(int i=0; i< [name length];i++){
        int a = [name characterAtIndex:i];
        if( a >= 0x4e00 && a <= 0x9fff){ //判斷是否為中文
            character +=2;
        }else{
            character +=1;
        }
    }
    LOG(@"%ld",character);
    if (character >=4 && character <=30) {
        return YES;
    }else{
        return NO;
    }
    
}

發佈留言