Reputation: 423
I have a word list stored in an NSArray
, I want to find all the words in it with the ending 'ing'.
Could someone please provide me with some sample/pseudo code.
Upvotes: 1
Views: 315
Reputation: 150565
Let's say you have an array defined:
NSArray *wordList = // you have the contents defined properly
Then you can enumerate the array using a block
// 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"
(I am using ARC in this code block)
I am giving an example using blocks because its gives you more options should you need them, and it's a more modern approach to enumerating collections. You could also do this with a concurrent enumeration and get some performance benefits as well.
Upvotes: 4
Reputation: 11476
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.
Typed from scratch, should work :)
Upvotes: 1
Reputation: 40211
Use NSPredicate
to filter NSArrays
.
NSArray *array = @[@"test", @"testing", @"check", @"checking"];
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF ENDSWITH 'ing'"];
NSArray *filteredArray = [array filteredArrayUsingPredicate:predicate];
Upvotes: 8
Reputation: 11962
Just loop through it and check the suffixes like that:
for (NSString *myString in myArray) {
if ([myString hasSuffix:@"ing"]){
// do something with myString which ends with "ing"
}
}
Upvotes: 2