iOS如何实现截取字符串中汉字功能
小编给大家分享一下iOS如何实现截取字符串中汉字功能,希望大家阅读完这篇文章之后都有所收获,下面让我们一起去探讨吧!
具体内容如下
写了一个简单的例子,从第一个汉字开始截取字符串。下面贴上代码:
#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 = 橙子
看完了这篇文章,相信你对"iOS如何实现截取字符串中汉字功能"有了一定的了解,如果想了解更多相关知识,欢迎关注行业资讯频道,感谢各位的阅读!