美文网首页
iOS实现截取字符串中汉字功能

iOS实现截取字符串中汉字功能

作者: 江河_ios | 来源:发表于2021-11-26 15:49 被阅读0次
    • (void)setContent:(NSString *)content
      {
      NSArray *array=[content componentsSeparatedByString:@"&"];
      NSMutableString *string=[NSMutableString new];
      for (int i = 0; i < array.count; i++) {
      NSString *chineseStr = [self getChineseStringWithString:array[i]];
      if (chineseStr.length>0) {
      [string appendString:chineseStr];
      [string appendString:@";"];
      }
      }
      _content = string;
      }
    • (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;
      }

    相关文章

      网友评论

          本文标题:iOS实现截取字符串中汉字功能

          本文链接:https://www.haomeiwen.com/subject/npcxxrtx.html