123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105 |
- //
- // NSString+hanzi.m
- // SmartLightForBigFish
- //
- // Created by coderYK on 2017/8/29.
- // Copyright © 2017年 RD. All rights reserved.
- //
- #import "NSString+hanzi.h"
- @implementation NSString (hanzi)
- - (NSString *)rds_getChineseString
- {
- //(unicode中文编码范围是0x4e00~0x9fa5)
- for (int i = 0; i < self.length; i++) {
- int utfCode = 0;
- void *buffer = &utfCode;
- NSRange range = NSMakeRange(i, 1);
-
- BOOL b = [self getBytes:buffer
- maxLength:2
- usedLength:NULL
- encoding:NSUTF16LittleEndianStringEncoding
- options:NSStringEncodingConversionExternalRepresentation
- range:range
- remainingRange:NULL];
-
- if (b && (utfCode >= 0x4e00 && utfCode <= 0x9fa5)) {
- return [self substringFromIndex:i];
- }
- }
- return nil;
- }
- - (NSInteger)rds_countStringByteLength
- {
- NSStringEncoding enc = CFStringConvertEncodingToNSStringEncoding(kCFStringEncodingGB_18030_2000);
- NSData* da = [self dataUsingEncoding:enc];
- NSInteger length = [da length];
- return length;
- }
- - (NSString *)subBytesOfstringToIndex:(NSInteger)index
- {
- NSInteger length = 0;
-
- NSInteger chineseNum = 0;
- NSInteger zifuNum = 0;
-
- for (int i = 0; i<[self length]; i++) {
- //截取字符串中的每一个字符
- NSString *s = [self substringWithRange:NSMakeRange(i, 1)];
- if ([self validateChineseChar:s])
- {
- if (length + 2 > index)
- {
- return [self substringToIndex:chineseNum + zifuNum];
- }
-
- length +=2;
-
- chineseNum +=1;
- }
- else
- {
- if (length +1 >index)
- {
- return [self substringToIndex:chineseNum + zifuNum];
- }
- length+=1;
-
- zifuNum +=1;
- }
- }
- return [self substringToIndex:index];
- }
- //检测中文或者中文符号
- - (BOOL)validateChineseChar:(NSString *)string
- {
- NSString *nameRegEx = @"[\\u0391-\\uFFE5]";
- if (![string isMatchesRegularExp:nameRegEx]) {
- return NO;
- }
- return YES;
- }
- //检测中文
- - (BOOL)validateChinese:(NSString*)string
- {
- NSString *nameRegEx = @"[\u4e00-\u9fa5]";
- if (![string isMatchesRegularExp:nameRegEx]) {
- return NO;
- }
- return YES;
- }
- - (BOOL)isMatchesRegularExp:(NSString *)regex {
- NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex];
- return [predicate evaluateWithObject:self];
- }
- @end
|