当前位置: 首页 > 工具软件 > iOS Hero > 使用案例 >

iOS 截取字符串中汉字 —— HERO博客

楚俊逸
2023-12-01

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

#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 = 橙子


 类似资料: