问题
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