在一些特定的情况下,我们需要判断字符串是否为纯汉字,还是只是含有汉字的情况。
我把它写成了一个分类,方便大家使用
NSString+Chinese.h
#import <Foundation/Foundation.h>
@interface NSString (Chinese)
/**
* 判断是否是纯汉字
*/
-(BOOL)isChinese;
/**
* 判断是否含有汉字
*/
-(BOOL)includeChinese;
@end
#import "NSString+Chinese.h"
@implementation NSString (Chinese)
/**
* 判断是否是纯汉字
*/
-(BOOL)isChinese{
NSString *match = @"(^[\u4e00-\u9fa5]+$)";
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF matches %@", match];
return [predicate evaluateWithObject:self];
}
/**
* 判断是否含有汉字
*/
-(BOOL)includeChinese{
for(int i=0; i< [self length];i++){
int a =[self characterAtIndex:i];
if( a >0x4e00&& a <0x9fff){
return YES;
}
}
return NO;
}
@end