How to Search a List of Names in iOS? - ios

So basically I want to use a UISearchBar to search an Array of Names.
Inside the Array the Names have this Format:
[FIRST NAME] ([SECOND NAME]) [LAST NAME]
Using
if (![string rangeOfString:seachTextPart].location == NSNotFound)
I have managed to search Names entering ONLY the FIRST NAME into the UISearchBar.
But as soon as I enter a SPACE i get NO RESULTS.
Also I want to be able to search by entering just the LAST NAME.
Can anyone please help me?
Thanks

Assuming your format is follow:name = #"[John]([James])[Smith]";
Searching [name rangeOfString:#"John"] would yield found.
Searching [name rangeOfString:#"John "] would yield not found, since #"John " is not in name
But in this case, [name rangeOfString:#"Smith"] would yield found.
Try this: Remove all spaces and lower case strings
searchTerm = [[searchTerm stringByReplacingOccurrencesOfString:#" " withString:#""] lowercaseString];
NSRange searchName = [[name lowercaseString] rangeOfString:searchTerm];
If you want to test, just simply do this"
if (searchName == 0) //it does not match

Byte's code works unless they type "John Smith." If you want something more robust you can use - (NSArray *)componentsSeparatedByString:(NSString *)separator and then search for any of the strings in the Array. So Typing "John Smith" would return all of the Johns and all of the Smiths
here:
NSArray *theTerms = [searchTerm componentsSeparatedByString:#" "];
then run a for loop through all of theTerms and check them against your names adding the ones that contain the search terms to an array and then displaying them.

Related

NSMutable String: How do I get the index of multiple spaces in a string?

I want to find the index of the 8th occurrence of " " so that I could split my string there. However all I can find is this line of code that gives me an array of all the occurrences of " ". Is there a function I can call that would give me this information?
int numberOfOccurences = [[myListString componentsSeparatedByString:#" "] count];
Edit 1: So far this is the solution I came up with:
if(numberOfOccurences > 8)
{
//find index of place where you want to split by picking an
//arbitrary number and finding the first white space
int index = (int)[[myListString substringFromIndex:45] rangeOfString:#" "].location;
NSLog(#"Index: %i", index);
//make substring
NSString *substringList1 = [myListString substringToIndex:(45+index)];
NSString *substringList2 = [myListString substringFromIndex:(45+index)];
}
There is no method to find the 8th space, but there are the building blocks you need.
The NSString method rangeOfString:options:range: will find the first occurrence of its first argument within the range specified by its third argument, it returns a range for the match. You simply start with the third argument being the whole string and then iterate reducing the range to search using the previous result.
If you are actually looking for white space and not simply a space you might consider the similar rangeOfCharactersFromSet methods.
If you don't really want the eighth space, but are trying to break a string at a given length, you can look at componentsSeparatedByString/componentsSeparatedByCharactersInSet and then reassemble the resultant “words" into strings of the appropriate length. You might also want to look at NSScanner.
HTH
With the explicit assumption that you are looking for the eighth space (and possibly needing to adjust the regex a little depending on character set), you could use a regular expression:
NSRegularExpression *exp = [NSRegularExpression regularExpressionWithPattern:#"^([^ ]* ){8}+"
options:0
error:NULL];
NSRange result = [exp rangeOfFirstMatchInString:input options:0 range:inputRange];
If result.location != NSNotFound then result.length gives you the index on which to split.

Remove BackEnd character in a 'NSString'

I'm facing a problem when I try to remove a character in a 'NSString'. The character is a backend (\n).
My 'NSString' is for example like this :
My text is
also in a second line
And I want to get all in one line like this :
My text is also in a second line
The problem is I don't know how to change this...
I tried to locate the '\n' characters with a loop :
for (int delete = 0; delete < myString.length; delete++)
{
if ([myString characterAtIndex:delete] == 10)
{
[myString stringByReplacingCharactersInRange:NSMakeRange(delete,0) withString:#" "];
}
}
Or things like :
myString = [myString stringByReplacingOccurrencesOfString:#"\r" withString:#" "];
(I see that \r could be the backend in a nslog...)
Nothings work..
Thank you for your help in advance !
myString = [myString stringByReplacingOccurrencesOfString:#"\n" withString:#""];
is correct.
If it doesn't work, then the assumption that there is a combination of "\" and "n" characters is wrong.
Do not use NSLog. NSLog already applies carriage returns to the string. Instead put a breakpoint on the line where we call stringByReplacing... and then hover over the myString. Wait a second or two and you will see the "original unformatted content"...this way you can check what you are really trying to replace..

NSString: Best way to check if string contains another string with special format?

I have a string representing fruits, separated by dot:
apple.orange.banana.watermelon
and each fruit may have a tag:
apple.orange.[old]banana.[juicy]watermelon
also there may be fruit names which are partially overlapping:
apple.orange.[old]banana.[juicy]strawberry.[fresh]berry
also the tags may be same as fruit names:
apple.orange.[old]banana.[berry]strawberry.[fresh]berry
I need to check if such a string contains a specified fruit, so given the above string and a fruit name, say "berry", I want to know the string contains "berry" and of course it should not tell me YES if "berry"'s not there but "strawberry" is.
A quick way came up in my mind is:
use componentsSeparatedByString to get an array of components (fruit names with tags)
go through each component, check if it has a tag (ie square brackets), remove it if YES
then check the remaining string is exactly the given fruit name
I cannot just use the whole string with rangeOfString because "berry" is a substring of "strawberry", I can't even first get components then check substring for each component because tags may be the same as fruit names.
I wonder is there any better way to do this? Better in terms of memory footprint and/or speed?
Thanks!
There are plenty of ways to do this.
You could use a regular expression.
You could split the string into parts.
But instead, let's notice that, when “berry” (the desired fruit) isn't the first or last fruit in the string, it's got to appear as either ]berry. or as .berry., and neither of those can match if “berry” is a substring.
So we can solve this problem quite simply putting a . on each end of the string before searching it for one of those patterns:
BOOL stringContainsFruit(NSString *string, NSString *fruit) {
string = [NSString stringWithFormat:#".%#.", string];
NSString *dotFruit = [NSString stringWithFormat:#".%#.", fruit];
if ([string rangeOfString:dotFruit].location != NSNotFound) {
return YES;
}
NSString *bracketFruit = [NSString stringWithFormat:#"]%#.", fruit];
if ([string rangeOfString:bracketFruit].location != NSNotFound) {
return YES;
}
return NO;
}

How do I search an NSString sentence with words separated by commas for a specific word in iOS7?

I came across a question that had an example using rangeOfString. How ever the first thing that came to mind was NSPredicate.
I have different strings that return words separated by sentences. For example I have one that returns "Male, Female".
What is the most efficient way to search either "Male" or "Female". I'd like to perform some actions if the word happens to be part of the sentence and if it doesn't.
NSDictionary with stored words separated by commas. I use different keys to grab specific bunch of words. Below I use the "selectedGenders" key which returns "Male, Female":
if ([combinedRefinementSelection valueForKey:#"selectedGenders"]) {
NSString *selectedGenders = [combinedRefinementSelection valueForKey:#"selectedGenders"];
// Show string in label so customer knows how their clothes items will be filtered
[[_thisController chosenGender] setText:selectedGenders];
}
I simply want to search selectedGenders and find out if Male or Female is part of the string.
As you said, rangeOfString works just fine.
NSString* sentence = #"Male, Female";
if ([sentence rangeOfString:#"Male"].location != NSNotFound)
{
NSLog(#"Male is found");
}
if ([sentence rangeOfString:#"Female"].location != NSNotFound)
{
NSLog(#"Female is found");
}

How do I use NSRange with this NSString?

I have the following NSString:
productID = #"com.sortitapps.themes.pink.book";
At the end, "book" can be anything.... "music", "movies", "games", etc.
I need to find the third period after the word pink so I can replace that last "book" word with something else. How do I do this with NSRange? Basically I need this:
partialID = #"com.sortitapps.themes.pink.";
You can try a backward search for the dot and use the result to get the desired range:
NSString *str = #"com.sortitapps.themes.pink.book";
NSUInteger dot = [str rangeOfString:#"." options:NSBackwardsSearch].location;
NSString *newStr =
[str stringByReplacingCharactersInRange:NSMakeRange(dot+1, [str length]-dot-1)
withString:#"something_else"];
You can use -[NSString componentsSeparatedByString:#"."] to split into components, create a new array with your desired values, then use [NSArray componentsJoinedByString:#"."] to join your modified array into a string again.
Well, although this isn't a generic solution for finding characters, in your particular case you can "cheat" and save code by doing this:
[productID stringByDeletingPathExtension];
Essentially, I'm treating the name as a filename and removing the last (and only the last) extension using the NSString method for this purpose.

Resources