在 Swift 中,componentsJoinedByString被 join(...)替换,因此在这里它只用空格替换非字母数字字符。
let charactersToRemove = NSCharacterSet.alphanumericCharacterSet().invertedSet
let strippedReplacement = " ".join(someString.componentsSeparatedByCharactersInSet(charactersToRemove))
对于 Swift2..。
var enteredByUser = field.text .. or whatever
let unsafeChars = NSCharacterSet.alphanumericCharacterSet().invertedSet
enteredByUser = enteredByUser
.componentsSeparatedByCharactersInSet(unsafeChars)
.joinWithSeparator("")
@implementation NSString(MyUtil)
- (NSString*) stripNonNumbers {
NSMutableString* res = [NSMutableString new];
//NSCharacterSet *numericSet = [NSCharacterSet decimalDigitCharacterSet];
for ( int i=0; i < self.length; ++i ) {
unichar c = [self characterAtIndex:i];
if ( c >= '0' && c <= '9' ) // this looks cleaner, but a bit slower: [numericSet characterIsMember:c])
[res appendFormat:@"%c", c];
}
return res;
}
@end
extension String {
/// Will strip all non alpha characters from a string
public var alpha: String {
return components(separatedBy: CharacterSet.alphanumerics.inverted).joined()
}
}