在目标c中的字符串数组中搜索字符串

Fil*_*ght 85 arrays objective-c nsstring ios

我想在目标c中搜索字符串数组中的特定字符串.有人可以在这方面帮助我吗?

Jer*_*myP 190

BOOL isTheObjectThere = [myArray containsObject: @"my string"];
Run Code Online (Sandbox Code Playgroud)

或者如果你需要知道它在哪里

NSUInteger indexOfTheObject = [myArray indexOfObject: @"my string"];
Run Code Online (Sandbox Code Playgroud)

我强烈建议您阅读有关NSArray文档.在发布您的问题之前最好这样做:-)


小智 45

您可以使用NSPredicate类来搜索字符串数组中的字符串.请参阅以下示例代码.

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];
Run Code Online (Sandbox Code Playgroud)

这是在字符串数组中搜索字符串的最有效方法