iOS: Is there a way to check if an NSArray object contains a certain character?

20,598

Solution 1

You can check if an NSArray contains an object with containsObject. If it's an array of characters represented as one-character strings, then the code is simple:

NSArray *array = @[@"a", @"b", @"c", @"d"];
BOOL contains = [array containsObject:@"c"];

There's no such thing as an NSArray of scalar types like 'c' char, since the NS collections contain only objects. The nearest thing to an array of chars is an NSString, which has a variety of ways to tell you if a character is present. The simplest looks like this:

NSString *string = @"[email protected]";
NSRange range = [string rangeOfString:@"c"];
BOOL contains = range.location != NSNotFound;

Solution 2

You have to cycle through each NSString in the array and check if it contains the substring.

This custom method shows how:

//assumes all objects in the array are NSStrings
- (BOOL)array:(NSArray *)array containsSubstring:(NSString *)substring {

    BOOL containsSubstring = NO;

    for (NSString *string in array) {

        if ([string rangeOfString:substring].location != NSNotFound) {
            containsSubstring = YES;
            break;
        }
    }
    return containsSubstring;
}

Usage:

NSMutableArray *array = [[NSMutableArray alloc] initWithCapacity:3];
[array addObject:@"hi"];
[array addObject:@"yo"];
[array addObject:@"[email protected]"];

BOOL containsSubstring = [self array:array containsSubstring:@"@"];

Solution 3

You could create a custom Category class of NSArray and add the following method:

- (BOOL) containsCharacter:(NSString *) character
{
    BOOL characterFound = NO;
    for (id object in self)
    {
        if ([object isKindOfClass:[NSString class]])
        {
            NSRange range = [object rangeOfString:character];
            if (range.location != NSNotFound)
            {
                characterFound = YES;
                break;
            }
        }
    }

    return characterFound;
}

Thanks, Michael

Share:
20,598
user3606054
Author by

user3606054

Updated on October 16, 2020

Comments

  • user3606054
    user3606054 over 3 years

    I need a way to know if an array has the character "@" in one of its string objects. The following code obviously doesn't work because it checks if an object just has the @ sign instead of checking if an object contains the @ sign. For example, if the user has [email protected] my if statement won't detect it. I need to see if a user has an email or not. I tried researching on how to accomplish this on stackoverflow, but no luck. Any tips or suggestions will be appreciated.

    if([answer containsObject:@"@"]){
      /// do function.                 
    }
    
  • kraftydevil
    kraftydevil almost 10 years
    also a great option. To make a category: File > New File > Objective-C Category > Set Category name to whatever and then select NSArray for the class