I'm looking for a quick and easy way to strip non-alphanumeric characters from an NSString. Probably something using an NSCharacterSet, but I'm tired and nothing seems to return a string containing only the alphanumeric characters in a string.
Thanks! I wound up just using NSCharacterSet, but this article led me down the right path.
Jeff Kelley
2009-11-01 15:57:36
cool, glad to have helped!
ennuikiller
2009-11-01 16:03:21
+5
A:
What I wound up doing was creating an NSCharacterSet and the -invertedSet
method that I found (it's a wonder what an extra hour of sleep does for documentation-reading abilities). Here's the code snippet, assuming that someString
is the string from which you want to remove non-alphanumeric characters:
NSCharacterSet *charactersToRemove =
[[ NSCharacterSet alphanumericCharacterSet ] invertedSet ];
NSString *trimmedReplacement =
[ someString stringByTrimmingCharactersInSet:charactersToRemove ];
trimmedReplacement
will then contain someString
's alphanumeric characters.
Jeff Kelley
2009-11-01 16:01:01
FYI, stringByTrimmingCharactersInSet: only removes characters from the beginning and end of the string. Maybe that's what you wanted.
Ken Aspeslagh
2010-01-19 16:14:33
Hmm, good point, Ken. I didn't know that. It still works for my needs, but that's good to know.
Jeff Kelley
2010-01-19 16:40:17