views:

46

answers:

3

Hi Everyone, I gotta little question about string Programming: I have an NSCharacterSet which contains all the characters I want to remove from my NSString.

How can I do that?

Thank you, Christian

+1  A: 

If you're not too worried about efficiency, a simple way would be [[myString componentsSeparatedByCharactersInSet:myCharacterSet] componentsJoinedByString:@""].

Otherwise, you could run through the characters in a loop, appending ones that weren't in the set onto a new string. If you do it that way, remember to use an NSMutableString for your result as you're building it up.

David
A: 
NSString *newString = [oldString stringByTrimmingCharactersInSet:charactersToRemove];

Where charactersToRemove - your NSCaracterSet instance.

jamapag
This will just remove characters from the left and right ends of the string.
David
A: 

You can use an NSScanner to scan through the string, scanning a chunk of characters-not-in-the-set, appending it to your result string, scanning the characters-in-the-set into a variable you otherwise ignore, and repeating until the scanner reaches the end.

Peter Hosey