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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2802171/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-30 17:13:10  来源:igfitidea点击:

String search in string array in objective c

iosobjective-carraysnsstring

提问by Filthy Knight

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

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

回答by JeremyP

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 :-)

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

回答by Rashid

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

您可以使用 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];

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

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

回答by Rahul K Rajan

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