SoFunction
Updated on 2025-04-12

iOS implements the function of intercepting Chinese characters in strings

This article shares the specific code of iOS intercepting Chinese characters in strings for your reference. The specific content is as follows

I wrote a simple example to intercept strings from the first Chinese character. The following code is posted:

#import ""
 
@interface ViewController ()
 
@end
 
@implementation ViewController
 
- (void)viewDidLoad {
 [super viewDidLoad];
 
 NSArray *array = @[@"03-15_01Apple", @"412 Banana", @"#7&@15 Orange"]; for (int i = 0; i < ; i++) {
  NSString *chineseStr = [self getChineseStringWithString:array[i]];
  NSLog(@"chineseStr = %@\n", chineseStr);
 }
}
 
- (NSString *)getChineseStringWithString:(NSString *)string
{
 //(Unicode Chinese encoding range is 0x4e00~0x9fa5) for (int i = 0; i < ; 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

Running results:

2016-03-22 22:10:23.639 HWEncodeTest[502:8824] chineseStr = Apple
2016-03-22 22:10:23.639 HWEncodeTest[502:8824] chineseStr = Banana
2016-03-22 22:10:23.640 HWEncodeTest[502:8824] chineseStr = orange

The above is all the content of this article. I hope it will be helpful to everyone's study and I hope everyone will support me more.