字符串

作者: DDY | 来源:发表于2016-11-16 21:00 被阅读27次

常规字符串NSString

字符串是否包含子串

// 利用range
[dateStr rangeOfString:@"an"].location == NSNotFound
// iOS 8.0 later
[dateStr containsString:@"an"];

判断只有数字、小数点和减号

#define NUMBERS @"0123456789.-"

#pragma mark -是否只包含数字,小数点,负号
- (BOOL)isOnlyhasNumberAndpointWithString:(NSString *)string
{
    NSCharacterSet *cs=[[NSCharacterSet characterSetWithCharactersInString:NUMBERS] invertedSet];
    NSString *filter=[[string componentsSeparatedByCharactersInSet:cs] componentsJoinedByString:@""];
    return [string isEqualToString:filter];
}

字符串截取

  • [str substringWithRange:NSMakeRange(m,n)] 从第m个开始截取n个
  • [str substringToIndex:n] 截取到第n个(n不在截取内)
  • [str substringFromIndex:n] 从第n个截取到末尾(包含n)

富文本NSMutableAttributedString

富文本属性

NSFontAttributeName : 字体,默认字体Helvetica(Neue) /字号12
NSForegroundColorAttributeNam : 字体颜色,取值为UIColor对象,默认黑色
NSBackgroundColorAttributeName : 字体区域背景色,取值为UIColor对象,默认nil,透明色
NSLigatureAttributeName : 连体属性,取值为NSNumber对象(整数),0没有连体字符,默认1连体字符
NSKernAttributeName : 字符间距,取值为NSNumber 对象(整数),正值间距加宽,负值变窄
NSStrikethroughStyleAttributeName : 删除线,取值为 NSNumber 对象(整数)
NSStrikethroughColorAttributeName : 删除线颜色,取值为UIColor对象,默认黑色
NSUnderlineStyleAttributeName : 下划线,取值为枚举NSUnderlineStyle中的值,与删除线类似
NSUnderlineColorAttributeName : 下划线颜色,取值为UIColor 对象,默认黑色
NSStrokeWidthAttributeName : 笔画宽度,取值为NSNumber 对象(整数),负值填充效果,正值中空效果
NSStrokeColorAttributeName : 填充部分颜色,不是字体颜色,取值为UIColor 对象
NSShadowAttributeName : 阴影属性,取值为NSShadow对象
NSTextEffectAttributeName : 文本特殊效果,取值为NSString对象,目前只有图版印刷效果可用:
NSBaselineOffsetAttributeName : 基线偏移值,取值为NSNumber(float),正值上偏,负值下偏
NSObliquenessAttributeName : 字形倾斜度,取值为NSNumber(float),正值右倾,负值左倾
NSExpansionAttributeName : 文本横向拉伸属性,取值为NSNumber(float),正值横向拉伸文本,负值横向压缩文本
NSWritingDirectionAttributeName : 文字书写方向,从左向右书写或者从右向左书写
NSVerticalGlyphFormAttributeName : 文字排版方向,取值为NSNumber对象(整数),0表示横排文本,1表示竖排文本
NSLinkAttributeName : 链接属性,点击后调用浏览器打开指定URL地址
NSAttachmentAttributeName : 文本附件,取值为NSTextAttachment对象,常用于文字图片混排
NSParagraphStyleAttributeName : 文本段落排版格式,取值为NSParagraphStyle对象



NSMutableAttributedString *attStr = [[NSMutableAttributedString alloc] initWithString:str];
    //格式调整
    NSMutableParagraphStyle *style = [[NSMutableParagraphStyle alloc] init];
    /**调行间距*/
    style.lineSpacing = 10;

    //字间距
    [attStr addAttribute:NSKernAttributeName value:@5 range:NSMakeRange(0, [str length])];
    //添加行间距
    [attStr addAttribute:NSParagraphStyleAttributeName value:style range:NSMakeRange(0, [str length])];

    //横竖排版 ---无效果
//    [attStr addAttribute:NSVerticalGlyphFormAttributeName value:@1 range:NSMakeRange(0, [str length])];
    //下画线
    [attStr addAttribute:NSUnderlineStyleAttributeName value:@1 range:NSMakeRange(0, [str length])];
    //边线宽度
    [attStr addAttribute:NSStrokeWidthAttributeName value:@1 range:NSMakeRange(10, 10)];
    //边线颜色
    [attStr addAttribute:NSStrokeColorAttributeName value:[UIColor redColor] range:NSMakeRange(10, 10)];

    //阴影--无效果
    [attStr addAttribute:NSShadowAttributeName value:@4 range:NSMakeRange(20, 10)];

        //下划线
    [attStr addAttribute:NSStrikethroughStyleAttributeName value:@2 range:NSMakeRange(20, 10)];
    [attStr addAttribute:NSStrikethroughColorAttributeName value:[UIColor redColor] range:NSMakeRange(20, 10)];

    //字体背影色
    [attStr addAttribute:NSBackgroundColorAttributeName value:[UIColor blueColor] range:NSMakeRange(45, 10)];

    //字体颜色
    [attStr addAttribute:NSForegroundColorAttributeName value:[UIColor orangeColor] range:NSMakeRange(60, 10)];

    //段落
    [attStr addAttribute:NSParagraphStyleAttributeName value:@6 range:NSMakeRange(70, 80)];

详见1
详见2

富文本计算高度

#pragma mark 文字高度
- (CGFloat)textH:(NSString *)text lineSpace:(CGFloat)lineSpace width:(CGFloat)width font:(UIFont *)font
{
    NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc]init];
    paragraphStyle.lineSpacing = lineSpace;
    NSDictionary *attributes = @{NSParagraphStyleAttributeName:paragraphStyle,NSFontAttributeName:font};
    CGSize size = [text boundingRectWithSize:CGSizeMake(width, MAXFLOAT)
                                     options:NSStringDrawingUsesLineFragmentOrigin
                                  attributes:attributes
                                     context:nil].size;
    return size.height;
}

改变子串颜色

+ (__kindof NSMutableAttributedString *_Nonnull)changeTotalString:(NSString *_Nonnull)totalString subStringArray:(NSArray *_Nonnull)subStringArray subStringColor:(UIColor *_Nonnull)color andFont:(UIFont *_Nonnull)font {
    NSMutableAttributedString *attributedStr = [[NSMutableAttributedString alloc] initWithString:totalString];
    for (NSString *rangeStr in subStringArray) {
        NSRange range = [totalString rangeOfString:rangeStr options:NSBackwardsSearch];
        [attributedStr addAttribute:NSForegroundColorAttributeName value:color range:range];
        [attributedStr addAttribute:NSFontAttributeName value:font range:range];
    }
    return attributedStr;
}

字符串中添加图片

- (NSAttributedString *)stringWithUIImage:(NSString *) contentStr {
    // 创建一个富文本
    NSMutableAttributedString * attriStr = [[NSMutableAttributedString alloc] initWithString:contentStr];
    // 修改富文本中的不同文字的样式
    [attriStr addAttribute:NSForegroundColorAttributeName value:[UIColor blueColor] range:NSMakeRange(0, 5)];
    [attriStr addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:20] range:NSMakeRange(0, 5)];

    /**
     添加图片到指定的位置
     */
    NSTextAttachment *attchImage = [[NSTextAttachment alloc] init];
    // 表情图片
    attchImage.image = [UIImage imageNamed:@"jiedu"];
    // 设置图片大小
    attchImage.bounds = CGRectMake(0, 0, 40, 15);
    NSAttributedString *stringImage = [NSAttributedString attributedStringWithAttachment:attchImage];
    [attriStr insertAttributedString:stringImage atIndex:2];

    // 设置数字为红色
    /*
    [attriStr addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:NSMakeRange(5, 9)];
    [attriStr addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:30] range:NSMakeRange(5, 9)];
    */
    //NSDictionary * attrDict = @{ NSFontAttributeName: [UIFont fontWithName: @"Zapfino" size: 15],
                               // NSForegroundColorAttributeName: [UIColor blueColor] };

    //创建 NSAttributedString 并赋值
    //_label02.attributedText = [[NSAttributedString alloc] initWithString: originStr attributes: attrDict];
    NSDictionary * attriBute = @{NSForegroundColorAttributeName:[UIColor redColor],NSFontAttributeName:[UIFont systemFontOfSize:30]};
    [attriStr addAttributes:attriBute range:NSMakeRange(5, 9)];

    // 添加表情到最后一位
    NSTextAttachment *attch = [[NSTextAttachment alloc] init];
    // 表情图片
    attch.image = [UIImage imageNamed:@"jiedu"];
    // 设置图片大小
    attch.bounds = CGRectMake(0, 0, 40, 15);

    // 创建带有图片的富文本
    NSAttributedString *string = [NSAttributedString attributedStringWithAttachment:attch];
    [attriStr appendAttributedString:string];

    return attriStr;
}

段落

// paragraph style
    _style =  [[NSParagraphStyle defaultParagraphStyle] mutableCopy];
    _style.alignment = NSTextAlignmentLeft;  //对齐
    _style.headIndent = 0.0f;//行首缩进
    _style.firstLineHeadIndent = 10.0f;//首行缩进
    _style.tailIndent = 0.0f;//行尾缩进
    _style.lineSpacing = 2.0f;//行间距


    NSAttributedString *attrText = [[NSAttributedString alloc] initWithString:_text attributes:@{ NSParagraphStyleAttributeName : _style}];
    
    UILabel *_content = [[UILabel alloc] init];
    _content.attributedText = attrText;

URL中含中文的解决

// 方法1:
NSString* encodedString = [urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
// 方法2:
NSString * encodedString = (NSString *)CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault,(CFStringRef)urlString,NULL,NULL,kCFStringEncodingUTF8);

如果URL含有已转义的%等符号时,会再次转义而导致错误.

查看方法2参数说明:

CFStringRef CFURLCreateStringByAddingPercentEscapes(CFAllocatorRef allocator,CFStringRef originalString, CFStringRef charactersToLeaveUnescaped, CFStringRef legalURLCharactersToBeEscaped,CFStringEncoding encoding);

因此做出修改,写出方法:

NSString *encodedString = (NSString *)CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault, (CFStringRef)urlString, (CFStringRef)@"!$&'()*+,-./:;=?@_~%#[]", NULL, kCFStringEncodingUTF8);

.
富文本

相关文章

  • Javascript知识点整合

    字符串 单行字符串: ‘字符串’或“字符串” 多行字符串: `多行字符串` 字符串操作: 字符串连接‘+’号 长度...

  • C++基础字符串

    字符串的构造 字符串特性描述 字符操作 字符串赋值 字符串连接 字符串比较 字符串查找 字符串替换 字符串删除 字...

  • iOS中的NSString与NSMutableString

    字符串的创建 字符串读写 字符串的比较 字符串的搜索 字符串截取 字符串替换 字符串与路径 字符串转换 NSMut...

  • iOS NSString用法总结

    字符串属性 字符串截取 字符串比较 字符串搜索 字符串拼接 字符串基本类型转换 字符串分行,分段 字符串列举(按条...

  • php 字符串常见方法汇总

    字符串拼接 字符串检索 字符串截取 字符串替换 字符串大小写转化 字符串转数组 字符串格式化

  • iOS 字符串截取、iOS 字符串替换、iOS 字符串分隔、iO

    iOS之字符串截取、iOS 字符串替换、iOS字符串分隔、iOS之字符串匹配、截取字符串、匹配字符串、分隔字符串 ...

  • PHP中字符串函数库常用函数解析 -- PHP 学习 (十一)

    常用字符串函数分类: 字符串长度, 字符串查找, 字符串大小写转换, 字符串截取, 字符串 ASCII, 字符串加...

  • Kotlin语言(二):字符串类型

    1、字符串定义 2、字符串删除空格 3、字符串比较 4、字符串切割 5、字符串截取 6、字符串替换 7、字符串模板

  • 字符串扩展

    求字符串大小 字符串解码、转换 字符串截取 字符串汉字处理 字符串 Mac地址 字符串进制转换

  • 2020-09-30字符串

    day8-字符串 字符串的操作 in 和 not in字符串1 in 字符串2 - 判断字符串1是否是字符串...

网友评论

      本文标题:字符串

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