本文实例为大家分享了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 = 橙子
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持编程网。