String search in string array in objective c

I want to search a specific string in the array of strings in objective c. Can somebody help me in this regard?


Solution 1:

BOOL isTheObjectThere = [myArray containsObject: @"my string"];

or if you need to know where it is

NSUInteger indexOfTheObject = [myArray indexOfObject: @"my string"];

I strongly recommend you read the documentation on NSArray. It's best to do that before posting your question :-)

Solution 2:

You can use NSPredicate class for searching strings in array of strings. See the below sample code.

NSMutableArray *cars = [NSMutableArray arrayWithObjects:@"Maruthi",@"Hyundai", @"Ford", @"Benz", @"BMW",@"Toyota",nil];

NSString *stringToSearch = @"i";

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF contains[c] %@",stringToSearch]; // if you need case sensitive search avoid '[c]' in the predicate

NSArray *results = [cars filteredArrayUsingPredicate:predicate];

This is the most efficient way for searching strings in array of strings

Solution 3:

NSMutableArray *cars = [NSMutableArray arrayWithObjects:@"Max",@"Hai", @"Fine", @"Bow", @"Bomb",@"Toy",nil];

NSString *searchText = @"i";
 NSArray *results = [cars filteredArrayUsingPredicate:predicate];

// if you need case sensitive search avoid '[c]' in the predicate

 NSPredicate *resultPredicate = [NSPredicate
                                predicateWithFormat:@"title contains[c] %@",
                                searchText];


searchResults = [cars  filteredArrayUsingPredicate:resultPredicate];