I have the need to replace a set of characters with a single character. Ok No problem. There are a slew of ways to go about this. Currently, I am implementing the following:
-(NSString *)spank:(NSString *)string
{
NSCharacterSet *buggers = [NSCharacterSet characterSetWithCharactersInString:BAD_CHARS];
return [[string componentsSeparatedByCharactersInSet:buggers]
componentsJoinedByString:GOOD_CHAR];
}
My problem is discovering other sets of characters that are in need of being replaced within that same string.
e.g.
#define BAD_CHARS @"`^"
#define GOOD_CHAR @"|"
#define TEST @"Lor*em` ipsum dolor ^sit amet"
...
clean = [self spank:TEST];
console log: clean = "Lor*em| ipsum dolor |sit amet"
But it would be nice to replace * with a different character. Other cases could be added later.
To solve this, I could:
Message spank repeatedly for the same string, granted I changed it's signature. (boring, repetitive, and inefficient)
-(NSString *)spank:(NSString *)string bad:(NSString *)badset good:(NSString *)good;
Use enumeration. (I have implemented this with success)
-(NSString *)spank:(NSString *)string { static NSDictionary *blackbook; if (!blackbook) blackbook = [NSDictionary dictionaryWithObjectsAndKeys: GOOD_CHAR_A, BAD_CHARS_A, GOOD_CHAR_B, BAD_CHARS_B, nil]; __block NSString *pure = string; [blackbook enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) { NSCharacterSet *buggers = [NSCharacterSet characterSetWithCharactersInString:key]; pure = [[pure componentsSeparatedByCharactersInSet:buggers] componentsJoinedByString:obj]; }]; return pure; }
Implement a coder from NSCoder. This is an area I haven't explored yet.
Use php. I have the option to purge the string with php before I return it to the client. Perhaps it would be done easier there. Thoughts?
Some other cleaner, easier way I haven't come up with yet but maybe you have.
Thanks in advance for any suggestions. I do have this working with solution #2. Just not as concise as I would like to see.