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.
}
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;
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:@"@"];
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With