2012-10-07 58 views
1

我有一個存儲在NSArray中的單詞列表,我想查找其中包含結尾'ing'的所有單詞。使用後綴搜索NSArray

有人請給我提供一些樣品/僞代碼。

+2

只是一句警告:您可能會發現,如果在您自己的方面沒有展示太多研究成果,問「能否請某人......」可能會吸引負面反應(降低投票數,收到選票等)所以:您做了什麼?到目前爲止解決問題? – Monolo

回答

8

使用NSPredicate過濾NSArrays

NSArray *array = @[@"test", @"testing", @"check", @"checking"]; 
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF ENDSWITH 'ing'"]; 
NSArray *filteredArray = [array filteredArrayUsingPredicate:predicate]; 
+0

+1使用謂詞 - 另一個好的方法來過濾數組。 – Abizern

1
NSMutableArray *results = [[NSMutableArray alloc] init]; 

// assuming your array of words is called array: 
for (int i = 0; i < [array count]; i++) 
{ 
    NSString *word = [array objectAtIndex: i]; 
    if ([word hasSuffix: @"ing"]) 
     [results addObject: word]; 
} 

// do some processing 

[results release]; // if you're not using ARC yet. 

從頭打字,應該工作:)

2

只是遍歷並檢查這樣的後綴:

for (NSString *myString in myArray) { 
    if ([myString hasSuffix:@"ing"]){ 
    // do something with myString which ends with "ing" 
    } 
} 
4

比方說,你有定義的數組:

NSArray *wordList = // you have the contents defined properly 

然後你就可以使用塊

// This array will hold the results. 
NSMutableArray *resultArray = [NSMutableArray new]; 

// Enumerate the wordlist with a block 
[wordlist enumerateObjectsUsingBlock:(id obj, NSUInteger idx, BOOL *stop) { 
    if ([obj hasSuffix:@"ing"]) { 
     // Add the word to the result list 
     [result addObject:obj]; 
    } 
}]; 

// resultArray now has the words ending in "ing" 

(我在此代碼塊使用ARC)

枚舉數組

我給出了一個使用塊的例子,因爲它給你更多的選擇,如果你需要它們,它是一個更現代的方法來枚舉集合。你也可以通過併發枚舉來實現,並獲得一些性能優勢。