iOS实现截取字符串中汉字功能

时间:2022-08-25 10:14:23

本文实例为大家分享了iOS截取字符串中汉字的具体代码,供大家参考,具体内容如下

写了一个简单的例子,从第一个汉字开始截取字符串。下面贴上代码:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
#import "ViewController.h"
 
@interface ViewController ()
 
@end
 
@implementation ViewController
 
- (void)viewDidLoad {
 [super viewDidLoad];
 
 NSArray *array = @[@"03-15_01苹果", @"412香蕉", @"#7&@15橙子"];
 for (int i = 0; i < array.count; i++) {
  NSString *chineseStr = [self getChineseStringWithString:array[i]];
  NSLog(@"chineseStr = %@\n", chineseStr);
 }
}
 
- (NSString *)getChineseStringWithString:(NSString *)string
{
 //(unicode中文编码范围是0x4e00~0x9fa5)
 for (int i = 0; i < string.length; i++) {
  int utfCode = 0;
  void *buffer = &utfCode;
  NSRange range = NSMakeRange(i, 1);
  
  BOOL b = [string getBytes:buffer maxLength:2 usedLength:NULL encoding:NSUTF16LittleEndianStringEncoding options:NSStringEncodingConversionExternalRepresentation range:range remainingRange:NULL];
  
  if (b && (utfCode >= 0x4e00 && utfCode <= 0x9fa5)) {
   return [string substringFromIndex:i];
  }
 }
 return nil;
}
 
@end

运行结果:

2016-03-22 22:10:23.639 HWEncodeTest[502:8824] chineseStr = 苹果
2016-03-22 22:10:23.639 HWEncodeTest[502:8824] chineseStr = 香蕉
2016-03-22 22:10:23.640 HWEncodeTest[502:8824] chineseStr = 橙子

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持服务器之家。

原文链接:https://blog.csdn.net/hero_wqb/article/details/50959011