1

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

我的字符串是

Äî;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);

我错过了什么?

4

3 回答 3

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);

在这个例子中 $ 被删除

于 2012-11-10T12:25:05.803 回答
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

于 2012-11-10T11:02:59.837 回答
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,您可以用唯一的 if 替换它。
有时如果看文档花费太多时间,您可以自己发明解决方案。很多人会不同意,当然单行解决方案更好,但如果您没有找到正确的文档方法,为什么要浪费时间?

于 2012-11-10T12:07:19.703 回答