Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to detect if NSString contains a particular character or not?

i have one NSString object , for ex:- ($45,0000)

Now i want to find if this string contains () or not

How can i do this?

like image 339
Sim Fox Avatar asked Jan 10 '13 19:01

Sim Fox


2 Answers

Are you trying to find if it contains at least one of ( or )? You can use -rangeOfCharacterFromSet::

NSCharacterSet *cset = [NSCharacterSet characterSetWithCharactersInString:@"()"];
NSRange range = [mystr rangeOfCharacterFromSet:cset];
if (range.location == NSNotFound) {
    // no ( or ) in the string
} else {
    // ( or ) are present
}
like image 183
Lily Ballard Avatar answered Oct 13 '22 20:10

Lily Ballard


The method below will return Yes if the given string contains the given char

-(BOOL)doesString:(NSString *)string containCharacter:(char)character
{
    return [string rangeOfString:[NSString stringWithFormat:@"%c",character]].location != NSNotFound;
}

You can use it as follows:

 NSString *s = @"abcdefg";

    if ([self doesString:s containCharacter:'a'])
        NSLog(@"'a' found");
    else
        NSLog(@"No 'a' found");


    if ([self doesString:s containCharacter:'h'])
        NSLog(@"'h' found");
    else
        NSLog(@"No 'h' found");

Output:

2013-01-11 11:15:03.830 CharFinder[17539:c07] 'a' found

2013-01-11 11:15:03.831 CharFinder[17539:c07] No 'h' found

like image 35
dloomb Avatar answered Oct 13 '22 20:10

dloomb