Remove Special Characters in NSString

Per comment of @Rostyslav Druzhchenko from on the selected answer of @MadhuP:

NSString *unfilteredString = @"!@#$%^&*()_+|abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
NSCharacterSet *notAllowedChars = [[NSCharacterSet alphanumericCharacterSet] invertedSet];
NSString *escapedString = [[unfilteredString componentsSeparatedByCharactersInSet:notAllowedChars] componentsJoinedByString:@""];
NSLog (@"Result: %@", escapedString);

This is the answer that will use alphanumericCharacterSet to handle multiple countries character set.


There are numerous ways of dealing with this. As an example, here's a solution using regular expressions. This is just an example. We don't know the entire range of special characters that you want to remove.

#import <Foundation/Foundation.h>

int main(int argc, const char * argv[])
{

    @autoreleasepool {
        NSRegularExpression *expression = [NSRegularExpression regularExpressionWithPattern:@"[,\\.`\"]"
                                                                                    options:0
                                                                                      error:NULL];
        NSString *sampleString = @"The \"new\" quick brown fox, who jumped over the lazy dog.";
        NSString *cleanedString = [expression stringByReplacingMatchesInString:sampleString
                                                                       options:0
                                                                         range:NSMakeRange(0, sampleString.length)
                                                                  withTemplate:@""];
        printf("cleaned = %s",[cleanedString UTF8String] );

    }
    return 0;
}

NSString *unfilteredString = @"!@#$%^&*()_+|abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
NSCharacterSet *notAllowedChars = [[NSCharacterSet characterSetWithCharactersInString:@"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"] invertedSet];
NSString *resultString = [[unfilteredString componentsSeparatedByCharactersInSet:notAllowedChars] componentsJoinedByString:@""];
NSLog (@"Result: %@", resultString);

TRY THIS IT MAY HELPS YOU