Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can NSRange determine if a snippet of text exists in a larger string?

I have a large string coming back from an http GET and I'm trying to determine if it has a specific snippet of text or not (please forgive my sins here)

My question is this: Can / Should I use NSRange to determine if this snippet of text does exist?

  NSRange textRange;
  textRange =[[responseString lowercaseString] rangeOfString:[@"hat" lowercaseString]];

  if(textRange.location != NSNotFound)
  {
    //do something magical with this hat
  }

Thank you in advance!

like image 286
Toran Billups Avatar asked Dec 19 '25 17:12

Toran Billups


1 Answers

You can check to see if the location is NSNotFound:

NSRange textRange = [[responseString lowercaseString] rangeOfString:@"hat"];
if (textRange.location == NSNotFound) {
    // "hat" is not in the string
}

If a string is not found, rangeOfString: returns {NSNotFound, 0}.

You could bundle this up into a category on NSString if you use it a lot:

@interface NSString (Helper)
- (BOOL)containsString:(NSString *)s;
@end

@implementation NSString (Helper)

- (BOOL)containsString:(NSString *)s
{
    return [self rangeOfString:s].location != NSNotFound;
}

@end
like image 59
mipadi Avatar answered Dec 21 '25 08:12

mipadi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!