从NSString中删除非字母数字字符

时间:2009-11-01 04:40:07

标签: cocoa cocoa-touch nsstring nscharacterset

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

9 个答案:

答案 0 :(得分:144)

我们可以通过拆分然后加入来做到这一点。对于componentsSeparatedByCharactersInSet:

,需要OS X 10.5+
NSCharacterSet *charactersToRemove = [[NSCharacterSet alphanumericCharacterSet] invertedSet];
NSString *strippedReplacement = [[someString componentsSeparatedByCharactersInSet:charactersToRemove] componentsJoinedByString:@""];

答案 1 :(得分:21)

在Swift中,componentsJoinedByStringjoin(...)取代,因此它只是用空格替换非字母数字字符。

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

答案 2 :(得分:19)

我最后做的是创建一个NSCharacterSet和我发现的-invertedSet方法(这对于文档阅读能力来说,这是一个多么奇怪的睡眠时间)。这是代码片段,假设someString是要从中删除非字母数字字符的字符串:

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

NSString *trimmedReplacement =
[ someString stringByTrimmingCharactersInSet:charactersToRemove ];
然后

trimmedReplacement将包含someString个字母数字字符。

答案 3 :(得分:6)

接受答案的Swift 3版本:

let unsafeChars = CharacterSet.alphanumerics.inverted
let myStrippedString = myString.components(separatedBy: unsafeChars).joined(separator: "")

答案 4 :(得分: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

答案 5 :(得分:0)

这是一个Swift版本的Cameron’s category作为扩展名:

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

答案 6 :(得分: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

答案 7 :(得分: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

答案 8 :(得分:0)

Swift 5,扩展:

extension String {

    /// Will strip all non alpha characters from a string
    public var alpha: String {
        return components(separatedBy: CharacterSet.alphanumerics.inverted).joined()
    }
}