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]; 这个方法取的是具体的第几个字符。

          

         

      

  • 相关阅读:
    Windows Vista 桌面窗口管理器(1)
    Thinking in Java读书笔记――数组
    php图片上传存储源码,可实现预览
    php at(@)符号的用法简介
    Apache如何添加虚拟目录
    也发个PHP人民币金额数字转中文大写
    PHP Get Current URL
    Zend Studio下的PHP代码调试
    PHP url 加密解密函数
    使用新浪微博php SDK的一点记录
  • 原文地址:https://www.cnblogs.com/yqlog/p/5258548.html
Copyright © 2011-2022 走看看