从一个NSString地带的非字母数字字符(Strip Non-Alphanumeric Chara

2019-09-03 08:22发布

我在寻找一个快速简便的方法,从剥离非字母数字字符NSString 。 可能是一些使用NSCharacterSet ,但我累了,似乎没有任何返回只包含字符串中的字母数字字符的字符串。

Answer 1:

我们可以通过拆分,然后加入做到这一点。 需要OS X 10.5+的componentsSeparatedByCharactersInSet:

NSCharacterSet *charactersToRemove = [[NSCharacterSet alphanumericCharacterSet] invertedSet];
NSString *strippedReplacement = [[someString componentsSeparatedByCharactersInSet:charactersToRemove] componentsJoinedByString:@""];


Answer 2:

在斯威夫特的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("")


Answer 3:

我清盘做是创造一个NSCharacterSet和-invertedSet方法,我发现(这是一个奇迹什么的睡眠一个小时做的文档阅读能力)。 下面的代码片段,假设someString是要删除非字母数字字符的字符串:

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

NSString *trimmedReplacement =
[ someString stringByTrimmingCharactersInSet:charactersToRemove ];

trimmedReplacement则包含someString的字母数字字符。



Answer 4:

雨燕3.0版本接受的答案的:

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


Answer 5:

清理范畴

我有一个方法调用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


Answer 6:

这里的斯威夫特版本卡梅伦的类别作为扩展:

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


Answer 7:

平原周期将是更快的执行时间,我认为:

@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


Answer 8:

这比提供的答案更有效的方式

+ (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


文章来源: Strip Non-Alphanumeric Characters from an NSString