zoukankan      html  css  js  c++  java
  • IOS UTF8中文字母数字 组合时长度截取

    //计算总共字数和限制字数的Index位置
    -(NSMutableArray *) unicodeLengthOfString: (NSString *) text
    {
        NSMutableArray *array = [NSMutableArray array];
        float asciiLength = 0;
        NSInteger  maxmumShowIndex  = 0;
        for (NSUInteger i = 0; i < text.length; i++) {
            unichar uc = [text characterAtIndex: i];
            if (isalnum(uc)) {
                asciiLength += 1.1;
            }else{
                asciiLength += isascii(uc) ? 1 : 2;
            }
            //计算可以显示的最大字数的Index位置
            if (asciiLength /2 < _maxMumCharactors) {
                maxmumShowIndex =i;
            }
        }
        //所有的字数
        NSUInteger unicodeLength = asciiLength / 2;
        
        if((NSInteger)asciiLength % 2) {
            unicodeLength++; 
        } 
        
        [array addObject:[NSNumber numberWithInteger:unicodeLength]];
        [array addObject:[NSNumber numberWithInteger:maxmumShowIndex]];
        return array;
    }
    

      代码解释: 设中文字数宽度为2, 非中文(isascii)宽度为1, 数字宽度为1.

         所有宽度之和为R, 所有字数之和为 H,  H = R / 2 + R%2,  

         上面的代码只是在计算刚刚超过限制字数时的Index位置。然后再截取或替换超过部分字符串。

      

      NSArray *titleTextLengthArray = [self unicodeLengthOfString:self.titleString];
        if ([[titleTextLengthArray firstObject] integerValue] >_maxMumCharactors) {
            NSInteger maxMumLength = [[titleTextLengthArray lastObject] integerValue];
            self.titleString = [self.titleString stringByReplacingCharactersInRange:NSMakeRange(maxMumLength, self.titleString.length-maxMumLength) withString:@"..."];
        }
    

        另外经过研究:self.titleString.length 其实是字符的个数。stringByReplacingCharactersInRange 这个方法也是针对字符数。 

          unichar uc = [text characterAtIndex: i]; 这个方法取的是具体的第几个字符。

          

         

      

  • 相关阅读:
    解释一下,@SpringBootApplication
    mybatis的一堆多映射使用配置
    SSM基础pom和xml的整合配置
    获取form表单所有数据最快方式
    两个大神的配置
    springmvc 注解详解
    自适应组件导航栏
    文本相似度的衡量之余弦相似度
    Pandas系列(十四)- 实战案例
    selenium常用操作
  • 原文地址:https://www.cnblogs.com/yqlog/p/5258548.html
Copyright © 2011-2022 走看看