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文章

Xcode模拟器相关操作

2020-2-26 11:21:12

iOS文章

iOS 单独设置某个控制器横屏

2020-2-26 13:21:44

个人中心
购物车
优惠劵
今日签到
有新私信 私信列表
搜索