2012-06-23 25 views
5

我想遍历NSString,并对每个具有特定条件的单词调用一个自定义函数(例如,“has 2'L's”)。我想知道接近的最好方法是什么。我应该使用查找/替换模式吗?块?在NSString的每个单词上调用一个方法

-(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. 
} 

回答

2

两种方式我知道循环数组,会为你工作如下:

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

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

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

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

另一种方法,–makeObjectsPerformSelector:withObject:,不会为你工作。它预计能够打电话给[word method:obj],这是你所期望的。

+0

对于中文,日文,德文等一些语言来说,空格在单词之间并不是明显的限制,因此Ken的方法是正确的。 – Krodak

1

如果你可以写正则表达式的标准,那么你也许可以做一个正则表达式匹配来获取这些话,然后将它们传递给你的方法convert:

您也可以使用componentsSeparatedByString:componentsSeparatedByCharactersInSet:将字符串拆分为单词数组,然后查看数组中的单词并检查它们是否符合您的条件。如果它们合适,则将它们传递给convert:

希望这会有所帮助。

-1

我会建议使用while循环来检查这样的字符串。

NSRange spaceRange = [sentenceContainingWords rangeOfString:@" "]; 
NSRange previousRange = (NSRange){0,0}; 
do { 
    NSString *wordString; 
    wordString = [sentenceContainingWord substringWithRange:(NSRange){previousRange.location+1,(spaceRange.location-1)-(previousRange.location+1)}]; 
    //use the +1's to not include the spaces in the strings 
    [self convert:wordString]; 
    previousRange = spaceRange; 
    spaceRange = [sentenceContainingWords rangeOfString:@" "]; 
} while(spaceRange.location != NSNotFound); 

此代码可能需要重写,因为它非常粗糙,但您应该明白。

编辑:刚才看到Jacob Gorban的文章,你应该这样做。是

18

要枚举字符串中的单词,应该使用-[NSString enumerateSubstringsInRange:options:usingBlock:]NSStringEnumerationByWordsNSStringEnumerationLocalized。列出的所有其他方法都使用识别可能不适合语言环境或与系统定义相对应的单词的方法。例如,由逗号而不是空白分隔的两个单词(例如“foo,bar”)不会被任何其他答案视为单独的单词,但它们都在Cocoa文本视图中。

[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 */; 
}]; 

至于记录的-enumerateSubstringsInRange:options:usingBlock:,如果你把它在一个可变的字符串,你可以放心地发生变异的字符串被内enclosingRange列举。所以,如果你想替换匹配的单词,你可以用类似[aString replaceCharactersInRange:substringRange withString:replacementString]的东西。

相关问题