I have an NSCharacterSet which contains all the characters I want to remove from my NSString.
How can I do that?
If you're not too worried about efficiency, a simple way would be [[myString componentsSeparatedByCharactersInSet:myCharacterSet] componentsJoinedByString:@""]
.
Otherwise, you could run through the characters in a loop, appending ones that weren't in the set onto a new string. If you do it that way, remember to use an NSMutableString
for your result as you're building it up.
Checkout the following code:
@implementation NSString(Replacing)
- (NSString *)stringByReplacingCharactersInSet:(NSCharacterSet *)charSet withString:(NSString *)aString {
NSMutableString *s = [NSMutableString stringWithCapacity:self.length];
for (NSUInteger i = 0; i < self.length; ++i) {
unichar c = [self characterAtIndex:i];
if (![charSet characterIsMember:c]) {
[s appendFormat:@"%C", c];
} else {
[s appendString:aString];
}
}
return s;
}
@end
If you specify a replacement string of @"" you would remove the characters in the set.
您可以使用NSScanner扫描字符串,扫描一大块字符 - 不在集合中,将其附加到结果字符串,将集合中的字符扫描到您忽略的变量中,然后重复直到扫描仪到达终点。
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.