从NSString中删除除+ - 运算符之外的所有特殊字符

时间:2012-11-10 10:51:12

标签: iphone objective-c ios nsstring

我想删除除+,空格和 - 之外的所有特殊字符。怎么可能?

我的字符串是

Äî;a[bRa]Co-Founder MobÄ: +91 9711700008

输出:

abRaCo-Founder Mob +91 9711700008

根据下面的答案,我更新了我的代码,但仍未成功。

NSMutableCharacterSet *special = [NSMutableCharacterSet characterSetWithCharactersInString:@"+ -"];
[special formUnionWithCharacterSet:[[NSCharacterSet alphanumericCharacterSet] invertedSet]];


NSString *temp=@"gaurav 1!@#!#@! kant !@#!@#!@#12kestwal ";

NSString *yourString = [temp stringByTrimmingCharactersInSet:special];

NSLog(@"%@",yourString);

我错过了什么?

3 个答案:

答案 0 :(得分:2)

比大型功能短得多。 :D以上:

id s = @"$bla++$bleb+$blub-$b";
NSMutableCharacterSet *ch = [[NSCharacterSet alphanumericCharacterSet] mutableCopy];
[ch invert];
[ch removeCharactersInString:@"+-"]; //make sure its not removed
s = [[s componentsSeparatedByCharactersInSet:ch] componentsJoinedByString:@""];
NSLog(@"%@ - %@",ch, s);

在此示例中,$被删除

答案 1 :(得分:0)

你可以试试吗,

NSString *yourString = @"Äî;a[bRa]Co-Founder MobÄ: +91 9711700008"

// thanks for Daij-Djan to point my mistake here
NSMutableCharacterSet *special = [[NSCharacterSet alphanumericCharacterSet] mutableCopy];
[special invert];
[special removeCharactersInString:@"+ -"]; 

// for this one I answer before Daij-Djan, please see edit version
//  note: I didn't offensive to anyone, please do not misunderstanding, thanks.
NSString *yourString =[[yourString componentsSeparatedByCharactersInSet:special]
 componentsJoinedByString:@""];

所以,它分开然后加入,感谢此链接Strip Non-Alphanumeric Characters from an NSString

答案 2 :(得分:0)

这是如何实现您想要做的事情的一个例子:

#import <Foundation/Foundation.h>

BOOL isWanted(unichar character)
{
    if(character>='a' && character<='z')
        return YES;
    if(character>='A' && character<='Z')
        return YES;
    if(character>='0' && character<='9')
        return YES;
    if(character=='-' || character=='+')
        return YES;
    return NO;
}

int main(int argc, char** argv)
{
    @autoreleasepool
    {
        NSString* string= @"Äî;a[bRa]Co-Founder MobÄ: +91 9711700008";
        NSMutableString* filteredString=[NSMutableString new];
        for(NSUInteger i=0; i<[string length];i++)
        {
            unichar character=[string characterAtIndex: i];
            if(isWanted(character))
                [filteredString appendString: [NSString stringWithFormat: @"%c",character]];
        }
        NSLog(@"%@",filteredString);
    }
    return 0;
}

如果你想在字符串中包含该字符,则isWanted函数返回YES。为了易读性,我没有使用很多逻辑OR,但只是如果是,你可以用唯一的if替换它。 有时候,如果观看文档需要花费太多时间,你可以自己发明解决方案。很多人都不同意,当然单线解决方案更好,但如果你找不到合适的文档化方法,为什么要浪费时间?