Replace character in NSMutableAttributedString

北慕城南 提交于 2019-12-10 21:48:14

问题


This works for a regular NSString:

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

But there is no such method for NSMutableAttributedString. How could I remove all instances of a comma in an 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))

Try this :)




回答2:


Do it before you create the attributed string, if you can or depending on how you source it. If you can't then you can use replaceCharactersInRange:withString: (or replaceCharactersInRange:withAttributedString:), but you need to know the range so you need to search and iterate yourself.




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



回答4:


You can initialize the attributed string with the stripped string with the designed init. No?




回答5:


The code could be applied from my answer 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];
    }


来源:https://stackoverflow.com/questions/29635950/replace-character-in-nsmutableattributedstring

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!