Im Batman
Im Batman

Reputation: 1876

String Search in two arrays in Objective C

I have this all country array in my code. i want to go through that array comparing another second array that to check it contains country name.

Example

NSString *str=@"Afghanistan, Albania, Algeria, American Samoa, Andorra, Angola, Anguilla, Antarctica,"; 
NSArray *arr = [str componentsSeparatedByString:@","];


NSString *myStr = "Toyota, Nissan, Bottle, Albania, Pen, Bag";
NSArray *myarr = [myStr componentsSeparatedByString:@","];

I want to compare this and if there is Country Name in MyStringArray that match with CountryArray[]then assign to string.

Upvotes: 0

Views: 322

Answers (3)

tuledev
tuledev

Reputation: 10317

int originLength = MyStringArray.count;

NSMutableArray *arr = [NSMutableArray arrayWithArray:MyStringArray];
[arr removeObjectsInArray: CountryArray];
int diff = [arr count];

if (originLength == diff) {
/// all diff
}
else {
}

Upvotes: 4

wattson12
wattson12

Reputation: 11174

The other answers will work but there is an NSArray method which makes this trivial:

NSArray *countryNamesArray = @[@"Australia", @"Japan", @"Sweden"];
NSArray *arrayContainingOneCountryName = @[@"Dog", @"Felafel", @"Australia"];

NSString *matchingCountry = [arrayContainingOneCountryName firstObjectCommonWithArray:countryNamesArray];
NSLog(@"%@", matchingCountry);

Upvotes: 2

Arc676
Arc676

Reputation: 4465

EDIT: never mind, use the other answer; it's better. I'll leave this here as an alternative method.

You can loop through the elements in MyStringArray and use [NSArray contains:] to check for the presence of the elements.

NSMutableArray *commonItems;
for (String *str in MyStringArray){
    if ([Country containsObject:str]){
        //Both arrays contains str
        [commonItems addObject:str];
    }
}
//commonItems now contains the country

I used an array because you didn't specify how many common items there might be.

Also, in componentsSeparatedByString should have @", " (mind the space)

Upvotes: 2

Related Questions