字符串

* 中英文混合字符串截取

- (NSString *)subStringByByteWithIndex:(NSInteger)index {
  NSInteger sum = 0;
  NSString *sourceStr = @"";
  NSString *subStr = [[NSString alloc] init];

  for(int i = 0; i<[sourceStr length]; i++) {
      unichar strChar = [sourceStr characterAtIndex:i];
      if(strChar < 256) {
        sum += 1; 
      } else {
        sum += 2;
      }
      if (sum >= index) {
        subStr = [sourceStr substringToIndex:i+1];
        return subStr;
      }   
   }
    return subStr;
  }

* 获取字符串字节数

 - (int)getByteNum:(NSString *)string {
    int strlength = 0;
    char* p = (char*)[string cStringUsingEncoding:NSUnicodeStringEncoding];

    for (int i=0 ; i<[string lengthOfBytesUsingEncoding:NSUnicodeStringEncoding] ;i++) {
        if (*p) {
          p++;
          strlength++;
        } else {
          p++;
        }
     }
    return strlength;
 }

* 多行字符串,最后一行的中间处省略多余字符

  UILabel *txtLabel = [[UILabel alloc] init];
  txtLabel.frame = CGRectMake(15, 460, 345, 100);
  txtLabel.numberOfLines = 2;
  txtLabel.backgroundColor = [UIColor cyanColor];
  [self.view addSubview:txtLabel];

  NSMutableAttributedString *attrStr = [[NSMutableAttributedString alloc] initWithString:@"上海东方明珠广播电视塔上海东方明珠广播电视塔上海东方明珠广播电视塔上海东方明珠广播电视塔上海东方明珠广播电视塔上海东方明珠广播电视塔"];
  NSMutableParagraphStyle *paraph =  [[NSMutableParagraphStyle alloc] init];
  paraph.baseWritingDirection = NSWritingDirectionRightToLeft;
  paraph.headIndent = 120;
  [attrStr addAttribute:NSParagraphStyleAttributeName value:paraph range:NSMakeRange(0, attrStr.length)];
  txtLabel.attributedText = attrStr;
  txtLabel.lineBreakMode = NSLineBreakByTruncatingTail;

效果如下:
屏幕快照 2018-09-18 下午5.17.59.png

你可能感兴趣的:(字符串)