替换NSMutableAttributedString中的字符

时间:2015-04-14 19:36:08

标签: ios nsstring nsmutableattributedstring

适用于常规NSString

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

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

5 个答案:

答案 0 :(得分:2)

let attrString = NSMutableAttributedString(string: "Hello <b>friend<b>")

attrString.mutableString.replaceOccurrencesOfString("<b>", withString: "", options: NSStringCompareOptions.CaseInsensitiveSearch, range: NSRange(location: 0, length: attrString.length))

试试这个:)

答案 1 :(得分:1)

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

答案 2 :(得分:1)

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)];

答案 3 :(得分:0)

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

答案 4 :(得分:0)

可以从我的回答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];
    }