调用NSString中每个单词的方法 [英] Call a method on every word in NSString

查看:115
本文介绍了调用NSString中每个单词的方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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


推荐答案

循环一个将为你工作的数组如下:

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];
}

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] ,这是从你期望的后退。

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.

这篇关于调用NSString中每个单词的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆