This question already has answers here:
How might I check if a particular NSString is present in an NSArray?
(3 answers)
Closed 9 years ago.
I want search (to check) one NSString in NSMutableArray. but I dont know about it.
NSMutableArray *a = [[NSMutableArray alloc]initWithObjects:#"Marco",#"christian",#"hon",#"John",#"fred",#"asdas", nil];
NSString *name = #"John";
I want to see is there name variable in a NSMutableArray variable ?
Use containsObject: method to check this :
NSMutableArray *a = [[NSMutableArray alloc]initWithObjects:#"Marco",#"christian",#"hon",#"John",#"fred",#"asdas", nil];
NSString *name = #"John";
if ([a containsObject:name]) {
// Your array cotains that object
}
Hope it helps you.
run a loop and check .
-(BOOL)array:(NSArray*)array containsString:(NSString*)name
{
for(NSString *str in array)
{
if([name isEqualToString:str])
return YES;
}
return NO;
}
In this way array find out object that it contains.
you can also use a single line
[array containsObject:name]
If you are also interested in the position of your element you can use
- (NSUInteger)indexOfObject:(id)anObject
it will return NSNotFound if the object is not in the array, or the index of the object
You can use the following code
if([a containsObject: name])
{
//here your code
}
[a containsObject:name]
This might help you.
I suggest you to use indexOfObject:. Because using this way you can not only check whether it exists but also get the index if it indeed exists.
NSMutableArray *array = [[NSMutableArray alloc] initWithObjects:#"Marco",#"christian",#"hon",#"John",#"fred",#"asdas", nil];
NSString *name = #"John";
NSInteger index = [array indexOfObject:name];
if (index != NSNotFound) {
NSLog(#"Find name %#", name);
} else {
NSLog(#"Name %# not fount", name);
}
Related
In my project I am getting response from the server in the form
response:
<JKArray 0x7fa2e09036b0>(
{
id = 23;
name = "Name1";
},
{
id = 24;
name = "Name2";
}
)
From this response array i am retrieving the objects at different indexes and then adding them in a mutableArray and then into a contactsDictionary.
self.contactsDictionary = [[NSMutableDictionary alloc] init];
for(int i=0 ; i < [response count] ; i++)
{
NSMutableArray *mutableArray=[[NSMutableArray alloc] init];
[mutableArray addObject:[response objectAtIndex:i]];
[self.contactsDictionary setObject:mutableArray forKey:[NSString stringWithFormat:#"%i",i]];
}
I want to retrieve data for Key #"name" from the contactsDictionary at some other location in the project. So how to do it.
Thanks in advance....
this is the wrong way like you are setting your contactsDictionary.
replace below line
[self.contactsDictionary setObject:mutableArray forKey:[NSString stringWithFormat:#"%i",i]];
with
[self.contactsDictionary setObject:[mutableArray objectAtIndex :i] forKey:[NSString stringWithFormat:#"%i",i]];
becuase everytime your array have new objects so your contacts dictionary's first value have one object then second value have two object. so you shouldn't do that.
now, if you want to retrieve name then call like
NSString *name = [[self.contactsDictionary objectForKey : #"1"]valueForKey : #"name"];
avoid syntax mistake if any because have typed ans here.
Update as per comment:
just take one mutablearray for exa,
NSMutableArray *arr = [[NSMutableArray alloc]init];
[arr addObject : name]; //add name string like this
hope this will help :)
Aloha from your respond I can give you answer Belo like that according to you response.
for(int i=0;i<[arrRes count];i++);
{
NSString *strId = [NSString stringWithFormat:#"%#",[[arrRes obectAtIndex:i]objectForKey:#"id"]];
NSString *StrName = [NSString stringWithFormat:#"%#",[[arrRes objectAtIndex:i]objectForKey:#"name"]];
NSLog(#"The ID is -%#",strId);
NSLog(#"The NAME is - %#",strName);
}
I am trying to find "Worf" inside the array of strings and then returning the BOOL of "YES" if I do find it, but if not, then return a BOOL of "NO".
So far this is what I have but it isn't working.
NSArray *myArray = #[#"Worf", #"son of Mogh", #"slayer of Gowron"];
NSString *myWorfString = #"Worf";
BOOL yesOrNo = NO;
for (NSString *task in myArray) {
if ([task isEqualToString: myWorfString]) {
yesOrNo = YES;
return yesOrNo;
} else {
return yesOrNo;
}
How would I input "return [myArray containsObject:myWolfString];" into my equation?
First of all you shouldn't compare objects with == unless you know what you are doing, since it compares memory addresses (where they are allocated) and not the contents. So two NSString* which points to two different instances which contain the same value are not equal according to ==.
You should use isEqualToString: or isEqualTo:.
In addition NSArray already contains this functionality, you don't need to reinvent the wheel:
NSArray *myArray = #[#"Worf", #"son of Mogh", #"slayer of Gowron"];
BOOL yesOrNo = [myArray containsObject:#"Worf"];
You have a logic error - you return immediately if the first item in the array is not #"Worf". While others have proposed solutions that will work, this one is most like your original code:
NSArray *myArray = #[#"Worf", #"son of Mogh", #"slayer of Gowron"];
NSString *myWorfString = #"Worf";
for (NSString *task in myArray)
if ([task isEqualToString: myWolfString])
return YES;
return NO;
Rather than go through the items one at a time, you can search the array concurrently, with lots of searches happening in parallel.
NSArray *myArray = #[#"Worf", #"son of Mogh", #"slayer of Gowron"];
NSString *myWorfString = #"Worf";
__block BOOL searchStringFound = NO;
[myArray enumerateObjectsWithOptions:NSEnumerationConcurrent usingBlock:^(NSString *string, NSUInteger idx, BOOL *stop) {
if ([string isEqualToString:myWorfString]) {
searchStringFound = YES;
*stop = YES;
}
}];
What's the advantage of this? It's faster, rather than search the array serially, you are doing it concurrently. Okay, so in this instance with such a small array it's unlikely to make much difference, but for larger arrays it could.
It's also a useful technique to use when looking for objects in collections. Because once you have found the object, you just set the stop parameter to YES to signal that no more enumerations need to be performed.
If you are looking for a substring:
- (BOOL)array:(NSArray *)array containsSubstring:(NSString *)substringToSearchFor
{
for (NSString *string in array) {
if (! [string isKindOfClass:[NSString class]])
continue; // skip objects that are not an NSString
if ([string rangeOfString:substringToSearchFor].location != NSNotFound)
return YES;
}
return NO;
}
Never compare strings with == use isEqualToString: instead.
You can just write:
return [myArray containsObject:myWolfString];
If you need to also check substring, you can use NSPredicate :
NSArray *myArray = #[#"Worf", #"son of Mogh", #"slayer of Gowron"];
NSString *myWolfString = #"Worf";
NSPredicate *pred = [NSPredicate predicateWithFormat:[NSString stringWithFormat:#"SELF CONTAINS [c] '%#'",myWolfString]];
NSArray *filteredArray = [myArray filteredArrayUsingPredicate:pred];
if ([filteredArray count])
{
NSLog(#"Index Of Object in main Array : %lu",(unsigned long)[myArray indexOfObject:filteredArray[0]]);
}
There are various ways you can find characters in NSArray and return YES in objective-c:-
1) By using NSPredicate
NSPredicate *pd=[NSPredicate predicateWithFormat:#"self MATCHES[CD] %#",myWorfString];
BOOL yesOrNo=[[NSNumber numberWithUnsignedLong:[[myArray filteredArrayUsingPredicate:pd]count]]boolValue];
2) Second using containsObjectapi
BOOL yesOrNo = [myArray containsObject:myWorfString];
3) Refer #EricS answer
NSArray *myArray = #[#"Worf", #"son of Mogh", #"slayer of Gowron"];
NSString *myWorfString = #"Worf";
BOOL yesOrNo = NO;
for (NSString *task in myArray)
{
if (([task isEqualToString: myWorfString]) || ([task rangeOfString:myWorfString].location != NSNotFound)) {
yesOrNo = YES;
break;
}
}
return yesOrNo;
Above code will return either array will contain as string or substring in array.
I have a NSString like this one:
NSString* allSeats = #"1_Male,2_Female,3_Female,4_Male";
I want to split the NSString based on the keywords _Male & _Female and then make two separate strings like these:
NSString* maleSeats = #"1,4";
NSString* femaleSeats = #"2,3";
based on the contents of allSeats variable declared above.
How it will be possible to split NSString and then make 2 seperate strings?
You have to do it yourself. There is no "all done" solution. There are a few ways to do it.
Note: I didn't try my code, I just wrote it, it may don't even compile. But the important thing is that you get the whole idea behind it.
One way could be this one:
NSString *maleSufffix = #"_Male";
NSString *femaleSufffix = #"_Female";
NSMutableArray *femaleSeatsArray = [[NSMutableArray alloc] init];
NSMutableArray *maleSeatsArray = [[NSMutableArray alloc] init];
NSArray *array = [allSeats componentsSeparatedByString:#","];
for (NSString *aSeat in array)
{
if ([aSeat hasSuffix:maleSuffix])
{
[maleSeatsArray addObject:[aSeat stringByReplacingOccurencesOfString:maleSuffix withString:#""]];
}
else if ([aSeat hasSuffix:femaleSuffix])
{
[femalSeatsArray addObject:[aSeat stringByReplacingOccurencesOfString:femaleSuffix withString:#""]];
}
else
{
NSLog(#"Unknown: %#", aSeat);
}
}
NSString *maleSeats = [maleSeatsArray componentsJoinedByString:#","];
NSString *femaleSeats = [femaleSeatsArray componentsJoinedByString:#","];
Of course, you could use different methods on array, enumerating it, use a NSMutableString instead of a NSMutableArray (for femaleSeatsArray or maleSeatsArray, and use adequate methods then in the for loop).
I derived an idea from Larme's Clue and it works as :
Make a method as and call it anywhere :
-(void)seperateSeat
{
maleSufffix = #"_Male";
femaleSufffix = #"_Female";
femaleSeatsArray = [[NSMutableArray alloc] init];
maleSeatsArray = [[NSMutableArray alloc] init];
array = [self.selectedPassengerSeat componentsSeparatedByString:#","];
for (aSeat in array)
{
if ([aSeat hasSuffix:maleSufffix])
{
aSeat = [aSeat substringToIndex:[aSeat length]-5];
NSLog(#"%# is value in final seats ::",aSeat );
[maleSeatsArray addObject:aSeat];
}
else if ([aSeat hasSuffix:femaleSufffix])
{
aSeat = [aSeat substringToIndex:[aSeat length]-7];
NSLog(#"%# is value in final seats ::",aSeat );
[femaleSeatsArray addObject:aSeat];
}
}
totalMales = [maleSeatsArray componentsJoinedByString:#","];
totalFemales = [femaleSeatsArray componentsJoinedByString:#","];
NSLog(#"maleSeatsAre::::%#",totalMales);
NSLog(#"maleSeatsAre::::%#",totalFemales);
}
I have this Array, and i need all first elements.
I can only read one with this
vc.ArrayListaFotos = [[listaImagens objectAtIndex:(indexPath.row * 3)] valueForKey:#"Caminho"];
But I can't read others first itens inside array 1,2,3...
Can someone help me please ?
You are using the wrong reference. You should do that:
NSMutableArray *arrayDeImagensParaOProdutoSelecionado = [NSMutableArray arrayWithObjects:nil];
for (NSArray *tempArray in listaImagens) {
if ([[NSString stringWithFormat:#"%#", [tempArray valueForKey:#"idProduto"]] isEqualToString:[NSString stringWithFormat:#"%#", [[produtos objectAtIndex:(indexPath.row * 3)] valueForKey:#"id"]]]) {
[arrayDeImagensParaOProdutoSelecionado addObject:tempArray];
}
}
Hope it help.
for(NSArray *innerArray in outerArray) {
NSObject *firstObject = [innerArray firstObject];
// do whatever you need to with firstObject
NSLog(#"%#",firstObject);
}
I want to scan NSString (case insensitive) to check whether all elements of an array contain in that String or not ?
Eg.
NSString *string1 = #"Java is pass by value : lets see how?";
NSString *string2 = #"Java is OOP Language";
NSArray *array = [[NSArray alloc] initWithObjects:#"Java",#"Pass",#"value", nil];
In this case string1 pass the test as it contain all keyword from array (i.e. Java,Pass,Value).
So, how can i achieve this functionality ?
I don't test it for speed, and it will fail on case-sensitive strings, but here's another solution (just in case)
NSArray *components = [string1 componentsSeparatedByString:#" "];
NSSet *textSet = [NSSet setWithArray:components];
NSSet *keywordsSet = [NSSet setWithArray:array];
BOOL result = [keywordsSet isSubsetOfSet:textSet];
Keep in mind that componentsSeparatedByString will tokenize very silly, like "how?" instead of "how" you need.
BOOL containsAll = YES;
for (NSString *test in array) {
if ([string1 rangeOfString:test].location == NSNotFound) {
containsAll = NO;
break;
}
}