-1

I wonder what I should do if I want a string to be "clean", ie tell the user to enter eg "+46 (70) - 22 88 88 2" in a box. Then I want the string to be cleaned so inputs are just numbers, ie, "46702288882", etc. How do you do it? Is it possible to exclude everything that is not numbers etc?

rmaddy
  • 314,917
  • 42
  • 532
  • 579
Stekarn
  • 11
  • 1

1 Answers1

1

Just create a NSCharacterSet and remove everything is not on it:

 NSCharacterSet *charactersToRemove =
 [[ NSCharacterSet alphanumericCharacterSet ] invertedSet ];

 NSString *trimmedReplacement =
 [[myString componentsSeparatedByCharactersInSet:charactersToRemove]
 componentsJoinedByString:@""];

You can use alphanumericCharacterSet if you want to keep characters and numbers, or just decimalDigitCharacterSet for numbers.

check documentation and different character sets here:

NSCharacterSet Apple Doc

Antonio MG
  • 20,382
  • 3
  • 43
  • 62