【问题标题】:Replace character in NSMutableAttributedString替换 NSMutableAttributedString 中的字符
【发布时间】:2015-06-20 13:42:33
【问题描述】:

这适用于普通的NSString

NSString *newString = [myString stringByReplacingOccurrencesOfString:@"," withString:@""];

但是NSMutableAttributedString没有这样的方法。如何删除 NSMutableAttributedString 中的所有逗号实例?

【问题讨论】:

    标签: ios nsstring nsmutableattributedstring


    【解决方案1】:
    let attrString = NSMutableAttributedString(string: "Hello <b>friend<b>")
    
    attrString.mutableString.replaceOccurrencesOfString("<b>", withString: "", options: NSStringCompareOptions.CaseInsensitiveSearch, range: NSRange(location: 0, length: attrString.length))
    

    试试这个:)

    【讨论】:

      【解决方案2】:

      在创建属性字符串之前执行此操作,如果可以或取决于您获取它的方式。如果你不能,那么你可以使用replaceCharactersInRange:withString:(或replaceCharactersInRange:withAttributedString:),但你需要知道范围,所以你需要自己搜索和迭代。

      【讨论】:

      • 我已经有了属性字符串。它可能包括文本附件等。我知道我必须使用 replaceCharactersInRange:withString 但就像你说的,我不知道范围。
      • 这就是为什么你会优先“修复”字符串。您可以获得string - 属性字符串的普通版本 - 并找到目标字符串的范围。但是,您需要在每次迭代中获取它,因为您将改变原始字符串,或跟踪突变范围......
      【解决方案3】:
      NSString *newString= "I want to ,show, you how to achieve this";
      NSMutableAttributedString *displayText = [[NSMutableAttributedString alloc] initWithString:[NSString stringWithFormat:@"%@",newString]];
      [[displayText mutableString] replaceOccurrencesOfString:@"," withString:@"" options:NSCaseInsensitiveSearch range:NSMakeRange(0, displayText.string.length)];
      

      【讨论】:

      • 第一个版本不起作用,因为您将一个不可变字符串分配给了 newString。第二个版本:你到底为什么要使用 stringWithFormat?
      【解决方案4】:

      您可以使用设计的 init 用剥离的字符串初始化属性字符串。没有?

      【讨论】:

        【解决方案5】:

        代码可以从我的回答here应用:

        NSAttributedString *attributedString = ...;
        NSAttributedString *anotherAttributedString = ...; //the string or characters which will replace
        
        while ([attributedString.mutableString containsString:@"replace"]) {
                NSRange range = [attributedString.mutableString rangeOfString:@"replace"];
                [attributedString replaceCharactersInRange:range  withAttributedString:anotherAttributedString];
            }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2018-02-05
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2014-06-01
          • 2011-12-17
          相关资源
          最近更新 更多