How to filter an array using NSPredicate for word combinations

[filteredArray filterUsingPredicate: [NSPredicate predicateWithFormat:@"self BEGINSWITH[cd] %@", searchText]]; 

filteredArray contains simple NSStrings. [hello, my, get, up, seven, etc ...];

It will give all lines starting with searchText .

But if the string is a combination of words like "my name" and searchText = name . How would NSPredicate look to achieve this?

UPDATE: And how should it be if I want to get the result with searchText = name , but not with searchText = ame ? Maybe like this:

  [filteredArray filterUsingPredicate: [NSPredicate predicateWithFormat: @"self BEGINSWITH[cd] %@ or self CONTENTS[cd] %@", searchText, searchText]]; 

But first, it should display lines starting with searchText , and only after those that contain searchText .

+4
source share
2 answers
 [NSPredicate predicateWithFormat:@"self CONTAINS[cd] %@", searchText]; 

EDIT after expanding the question

 NSArray *beginMatch = [filteredArray filteredArrayUsingPredicate: [NSPredicate predicateWithFormat: @"self BEGINSWITH[cd] %@", searchText]]; NSArray *anyMatch = [filteredArray filteredArrayUsingPredicate: [NSPredicate predicateWithFormat: @"self CONTAINS[cd] %@", searchText]]; NSMutableArray *allResults = [NSMutableArray arrayWithArray:beginMatch]; for (id obj in anyMatch) { if (![allResults containsObject:obj]) { [allResults addObject:obj]; } } filteredArray = allResults; 

This will be the result in the desired order without duplicate entries.

+5
source

EDIT Actually begins by checking from the beginning of the line to the length of the search string. if an exact match is found, then its filtered

 if u have name game tame lame search Text : ame filtered text would be: none 

It also contains a check from the beginning of the line to the length of the search string, but if the found stage is a search, medium or final exact search, then it is filtered.

 if u have name game tame lame search Text : ame filtered text would be: name game tame lame because all has ame 

 [NSPredicate predicateWithFormat:@"self CONTAINS '%@'", searchText]; 
+2
source

Source: https://habr.com/ru/post/1435250/


All Articles