Tuesday, May 24, 2011

Code Snippet: Word Filter

In objective-C, you are not provide with any method to filter our any specific word from a string. Today we will see the implementation of a method which could be used for such filtering of words or replacing them with another word.
Our word filter will be pretty simple. We will create an NSDictionary where the keys will be swear words and the values will be their replacements. We will then enumerate over the keys of the dictionary and replace them in display text with their values.

To do so, just call the following method once you have a string entered inside the UITextField.
-(IBAction) filterWord:(id)sender {
UITextField * textField = (UITextField *) sender;

NSDictionary * filteredWords = [NSDictionary dictionaryWithObjectsAndKeys:
@"Worst band ever",@"Nickelback",
@"hot dog",@"douche bag",nil];
NSString * newString = textField.text;

for(NSString * naughtyWord in filteredWords.allKeys) {
NSString * goodWord = [filteredWords objectForKey:naughtyWord];
NSLog(@"replacing %@ ",naughtyWord);
newString = [newString stringByReplacingOccurrencesOfString:naughtyWord

NSLog(@"New string -> %s", newString);

This way you could replace all the occurrences of any word/phrase with another one.