NSString+hanzi.m 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105
  1. //
  2. // NSString+hanzi.m
  3. // SmartLightForBigFish
  4. //
  5. // Created by coderYK on 2017/8/29.
  6. // Copyright © 2017年 RD. All rights reserved.
  7. //
  8. #import "NSString+hanzi.h"
  9. @implementation NSString (hanzi)
  10. - (NSString *)rds_getChineseString
  11. {
  12. //(unicode中文编码范围是0x4e00~0x9fa5)
  13. for (int i = 0; i < self.length; i++) {
  14. int utfCode = 0;
  15. void *buffer = &utfCode;
  16. NSRange range = NSMakeRange(i, 1);
  17. BOOL b = [self getBytes:buffer
  18. maxLength:2
  19. usedLength:NULL
  20. encoding:NSUTF16LittleEndianStringEncoding
  21. options:NSStringEncodingConversionExternalRepresentation
  22. range:range
  23. remainingRange:NULL];
  24. if (b && (utfCode >= 0x4e00 && utfCode <= 0x9fa5)) {
  25. return [self substringFromIndex:i];
  26. }
  27. }
  28. return nil;
  29. }
  30. - (NSInteger)rds_countStringByteLength
  31. {
  32. NSStringEncoding enc = CFStringConvertEncodingToNSStringEncoding(kCFStringEncodingGB_18030_2000);
  33. NSData* da = [self dataUsingEncoding:enc];
  34. NSInteger length = [da length];
  35. return length;
  36. }
  37. - (NSString *)subBytesOfstringToIndex:(NSInteger)index
  38. {
  39. NSInteger length = 0;
  40. NSInteger chineseNum = 0;
  41. NSInteger zifuNum = 0;
  42. for (int i = 0; i<[self length]; i++) {
  43. //截取字符串中的每一个字符
  44. NSString *s = [self substringWithRange:NSMakeRange(i, 1)];
  45. if ([self validateChineseChar:s])
  46. {
  47. if (length + 2 > index)
  48. {
  49. return [self substringToIndex:chineseNum + zifuNum];
  50. }
  51. length +=2;
  52. chineseNum +=1;
  53. }
  54. else
  55. {
  56. if (length +1 >index)
  57. {
  58. return [self substringToIndex:chineseNum + zifuNum];
  59. }
  60. length+=1;
  61. zifuNum +=1;
  62. }
  63. }
  64. return [self substringToIndex:index];
  65. }
  66. //检测中文或者中文符号
  67. - (BOOL)validateChineseChar:(NSString *)string
  68. {
  69. NSString *nameRegEx = @"[\\u0391-\\uFFE5]";
  70. if (![string isMatchesRegularExp:nameRegEx]) {
  71. return NO;
  72. }
  73. return YES;
  74. }
  75. //检测中文
  76. - (BOOL)validateChinese:(NSString*)string
  77. {
  78. NSString *nameRegEx = @"[\u4e00-\u9fa5]";
  79. if (![string isMatchesRegularExp:nameRegEx]) {
  80. return NO;
  81. }
  82. return YES;
  83. }
  84. - (BOOL)isMatchesRegularExp:(NSString *)regex {
  85. NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex];
  86. return [predicate evaluateWithObject:self];
  87. }
  88. @end