iOS 将一串字符里面的某个字符全部标志出来

Posted 羊羊羊

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了iOS 将一串字符里面的某个字符全部标志出来相关的知识,希望对你有一定的参考价值。

    NSMutableString * mutStr = [NSMutableString stringWithString:@"aaabbbbaaaccc"];
    NSString * str = @"a";
    NSRange range = {0,mutStr.length};
    [mutStr replaceOccurrencesOfString:@" " withString:@"" options:NSLiteralSearch range:range];
    [mutStr replaceOccurrencesOfString:@"\\n" withString:@"" options:NSLiteralSearch range:range];
    
    NSMutableAttributedString * attr = [[NSMutableAttributedString alloc]initWithString:mutStr];
    NSError * error;
    NSRegularExpression * express = [NSRegularExpression regularExpressionWithPattern:str options:NSRegularExpressionCaseInsensitive error:&error];
    NSArray<NSTextCheckingResult *> * result = [express matchesInString:mutStr options:0 range:range];
    for (NSTextCheckingResult * match in result) {
        NSRange range = [match range];
        [attr addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:range];
    }
    
    UILabel * lbl = [[UILabel alloc]initWithFrame:CGRectMake(100, 100, 200, 40)];
    [self.view addSubview:lbl];
    lbl.textColor = [UIColor blueColor];
    lbl.attributedText = attr;

  

以上是关于iOS 将一串字符里面的某个字符全部标志出来的主要内容,如果未能解决你的问题,请参考以下文章