Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call a method on every word in NSString

I would like to loop through an NSString and call a custom function on every word that has certain criterion (For example, "has 2 'L's"). I was wondering what the best way of approaching that was. Should I use Find/Replace patterns? Blocks?

-(NSString *)convert:(NSString *)wordToConvert{
    /// This I have already written
    Return finalWord;
}

-(NSString *) method:(NSString *) sentenceContainingWords{
    // match every word that meets the criteria (for example the 2Ls) and replace it with what convert: does. 
}
like image 901
Faz Ya Avatar asked Jun 23 '12 16:06

Faz Ya


2 Answers

To enumerate the words in a string, you should use -[NSString enumerateSubstringsInRange:options:usingBlock:] with NSStringEnumerationByWords and NSStringEnumerationLocalized. All of the other methods listed use a means of identifying words which may not be locale-appropriate or correspond to the system definition. For example, two words separated by a comma but not whitespace (e.g. "foo,bar") would not be treated as separate words by any of the other answers, but they are in Cocoa text views.

[aString enumerateSubstringsInRange:NSMakeRange(0, [aString length])
                            options:NSStringEnumerationByWords | NSStringEnumerationLocalized
                         usingBlock:^(NSString *substring, NSRange substringRange, NSRange enclosingRange, BOOL *stop){
    if ([substring rangeOfString:@"ll" options:NSCaseInsensitiveSearch].location != NSNotFound)
        /* do whatever */;
}];

As documented for -enumerateSubstringsInRange:options:usingBlock:, if you call it on a mutable string, you can safely mutate the string being enumerated within the enclosingRange. So, if you want to replace the matching words, you can with something like [aString replaceCharactersInRange:substringRange withString:replacementString].

like image 66
Ken Thomases Avatar answered Sep 24 '22 15:09

Ken Thomases


The two ways I know of looping an array that will work for you are as follows:

NSArray *words = [sentence componentsSeparatedByCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];

for (NSString *word in words)
{
    NSString *transformedWord = [obj method:word];
}

and

NSArray *words = [sentence componentsSeparatedByCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];

[words enumerateObjectsWithOptions:NSEnumerationConcurrent usingBlock:^(id word, NSUInteger idx, BOOL *stop){
    NSString *transformedWord = [obj method:word];
}];

The other method, –makeObjectsPerformSelector:withObject:, won't work for you. It expects to be able to call [word method:obj] which is backwards from what you expect.

like image 45
Jeffery Thomas Avatar answered Sep 23 '22 15:09

Jeffery Thomas