Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.                 
}
like image 538
user3606054 Avatar asked Jun 17 '14 15:06

user3606054


2 Answers

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;
like image 97
danh Avatar answered Oct 11 '22 18:10

danh


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:@"@"];
like image 31
kraftydevil Avatar answered Oct 11 '22 19:10

kraftydevil