Warrior
Warrior

Reputation: 39374

Remove Special characters in objective c

I want to remove the special characters from the file name. Please find the below code. I am have issue in removing the . from the file name, my code removes the .in the extension too.

Ex filename = atf.bac.xlsx
Expected result: atfbac.xlsx
Current Behavior:atfbacxlsx


NSCharacterSet *doNotWant = [NSCharacterSet characterSetWithCharactersInString:@".#%;:?,/|\[]{}@$%^*"];
fileName = [[fileName componentsSeparatedByCharactersInSet: doNotWant] componentsJoinedByString: @""];

Upvotes: 0

Views: 1354

Answers (1)

vadian
vadian

Reputation: 285069

You have to treat the string as a filename in a path or URL

  • Save the file extension temporarily.
  • Delete the file extension.
  • Remove the unwanted characters.
  • Add the file extension.

    NSString *fileName = @"atf.bac.xlsx";
    NSString *extension = fileName.pathExtension;
    NSString *baseName = [fileName stringByDeletingPathExtension];
    NSCharacterSet *doNotWant = [NSCharacterSet characterSetWithCharactersInString:@".#%;:?,/|\[]{}@$%^*"];
    fileName = [[[baseName componentsSeparatedByCharactersInSet: doNotWant] componentsJoinedByString: @""] stringByAppendingPathExtension:extension];
    NSLog(@"%@",fileName);
    

Upvotes: 8

Related Questions