Warrior Warrior - 16 days ago 8
iOS Question

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: @""];

Answer

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