73

我正在寻找一种快速简便的方法来从NSString. 可能是使用 的东西NSCharacterSet,但我很累,似乎没有任何东西返回一个只包含字符串中的字母数字字符的字符串。

4

9 回答 9

148

我们可以通过拆分然后加入来做到这一点。组件SeparatedByCharactersInSet 需要 OS X 10.5+:

NSCharacterSet *charactersToRemove = [[NSCharacterSet alphanumericCharacterSet] invertedSet];
NSString *strippedReplacement = [[someString componentsSeparatedByCharactersInSet:charactersToRemove] componentsJoinedByString:@""];
于 2011-07-02T02:20:14.663 回答
21

在 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("")

如果您只想删除一个字符,例如删除所有返回...

 enteredByUser = enteredByUser
         .componentsSeparatedByString("\n")
         .joinWithSeparator("")
于 2014-10-13T10:25:16.733 回答
19

我最终做的是创建一个 NSCharacterSet 和-invertedSet我发现的方法(奇怪的是,额外的一小时睡眠对文档阅读能力有什么作用)。这是代码片段,假设这someString是您要从中删除非字母数字字符的字符串:

NSCharacterSet *charactersToRemove =
[[ NSCharacterSet alphanumericCharacterSet ] invertedSet ];

NSString *trimmedReplacement =
[ someString stringByTrimmingCharactersInSet:charactersToRemove ];

trimmedReplacement然后将包含someString' 的字母数字字符。

于 2009-11-01T16:01:01.597 回答
8

Swift 3 版本的已接受答案:

let unsafeChars = CharacterSet.alphanumerics.inverted
let myStrippedString = myString.components(separatedBy: unsafeChars).joined(separator: "")
于 2017-04-25T20:56:45.593 回答
1

清理类别

我有一个方法调用stringByStrippingCharactersInSet:stringByCollapsingWhitespace这可能很方便直接插入。

@implementation NSString (Cleanup)

- (NSString *)clp_stringByStrippingCharactersInSet:(NSCharacterSet *)set
{
    return [[self componentsSeparatedByCharactersInSet:set] componentsJoinedByString:@""];
}

- (NSString *)clp_stringByCollapsingWhitespace
{
    NSArray *components = [self componentsSeparatedByCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
    components = [components filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"self <> ''"]];

    return [components componentsJoinedByString:@" "];
}

@end
于 2014-05-12T10:07:18.850 回答
1

斯威夫特 5,扩展:

extension String {

    /// Will strip all non alpha characters from a string
    public var alpha: String {
        return components(separatedBy: CharacterSet.alphanumerics.inverted).joined()
    }
}
于 2021-06-02T09:16:11.573 回答
0

这是作为扩展的Cameron 类别的 Swift 版本:

extension String {

    func stringByStrippingCharactersInSet(set:NSCharacterSet) -> String
    {
        return (self.componentsSeparatedByCharactersInSet(set) as NSArray).componentsJoinedByString("")
    }

    func stringByCollapsingWhitespace() -> String
    {
        var components:NSArray = self.componentsSeparatedByCharactersInSet(NSCharacterSet.whitespaceCharacterSet())
        let predicate = NSPredicate(format: "self <> ''", argumentArray: nil)
        components = components.filteredArrayUsingPredicate(predicate)

        return components.componentsJoinedByString(" ")
    }
}
于 2015-01-26T00:50:54.760 回答
0

我认为简单的循环将是更快的执行时间:

@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
于 2015-06-05T10:48:34.337 回答
0

这是比提供的答案更有效的方法

+ (NSString *)alphanumericString:(NSString *)s {

    NSCharacterSet * charactersToRemove = [[NSCharacterSet alphanumericCharacterSet] invertedSet];
    NSMutableString * ms = [NSMutableString stringWithCapacity:[s length]];
    for (NSInteger i = 0; i < s.length; ++i) {
        unichar c = [s characterAtIndex:i];
        if (![charactersToRemove characterIsMember:c]) {
            [ms appendFormat:@"%c", c];
        }
    }
    return ms;

}

或作为类别

@implementation NSString (Alphanumeric)

- (NSString *)alphanumericString {

    NSCharacterSet * charactersToRemove = [[NSCharacterSet alphanumericCharacterSet] invertedSet];
    NSMutableString * ms = [NSMutableString stringWithCapacity:[self length]];
    for (NSInteger i = 0; i < self.length; ++i) {
        unichar c = [self characterAtIndex:i];
        if (![charactersToRemove characterIsMember:c]) {
            [ms appendFormat:@"%c", c];
        }
    }
    return ms;

}

@end
于 2017-05-19T12:34:24.600 回答