Arun
Arun

Reputation: 3456

How to find out a specific character is present in a NSString or not?

I have two NSStrings named country and searchtext. I need to check whether the country contains the searchtext.

Eg: country = Iceland and searchtext = c, here the word iceland contains the character 'c'.

Thanks.

Upvotes: 15

Views: 30148

Answers (3)

Rajesh Loganathan
Rajesh Loganathan

Reputation: 11247

Very simple... try this

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

Upvotes: 2

Sirji
Sirji

Reputation: 554

NSString *st =    @"Iceland";
NSString *t_st = @"c";      
NSRange rang =[st rangeOfString:t_st options:NSCaseInsensitiveSearch];

   if (rang.length == [t_st length]) 
   {
          NSLog(@"done");
   }
   else
   {
          NSLog(@"not done");
   }

Upvotes: 8

Dennis Bliefernicht
Dennis Bliefernicht

Reputation: 5157

Try this:

NSRange range = [country rangeOfString:searchtext];
if (range.location != NSNotFound)
{
}

You also have the position (location) and length of your match (uninteresting in this case but might be interesting in others) in your range object. Note that searchtext must not be nil. If you are only interested in matching (and not the location) you can even condense this into

if ([country rangeOfString:searchtext].location != NSNotFound)
{
}

Upvotes: 45

Related Questions