Search code examples
iphoneobjective-cnsarraycharacternsrange

Match NSArray of characters Objective-C


I have to match the number of occurrences of n special characters in a string.
I thought to create an array with all these chars (they are 20+) and create a function to match each of them.
I just have the total amount of special characters in the string, so I can make some math count on them.

So in the example:

NSString *myString = @"My string #full# of speci@l ch@rs & symbols";
NSArray *myArray = [NSArray arrayWithObjects:@"#",@"@",@"&",nil];

The function should return 5.

Would it be easier match the characters that are not in the array, take the string length and output the difference between the original string and the one without special chars?
Is this the best solution?


Solution

  • NSString *myString = @"My string #full# of speci@l ch@rs & symbols";
    
      //even in first continuous special letters it contains -it will return 8
    
    //NSString *myString = @"#&#My string #full# of speci@l ch@rs & symbols";
    
    
    
    NSArray *arr=[myString componentsSeparatedByCharactersInSet:[NSMutableCharacterSet characterSetWithCharactersInString:@"#@&"]];
    
    NSLog(@"resulted string : %@ \n\n",arr);
    
    NSLog(@"count of special characters : %i \n\n",[arr count]-1);
    

    OUTPUT:

    resulted string : (

    "My string ",
    
    full,
    
    " of speci",
    
    "l ch",
    
    "rs ",
    
    " symbols"
    

    )

    count of special characters : 5