Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSString question - rangeOfString method

I am having an issue that I can't figure out.

I'm trying to run the rangeOfString method on a string, and I'm not sure how to determine if the string was not found. For example:

NSRange range = [@"abc" rangeOfString:@"d" options:NSCaseInsensitiveSearch range:NSMakeRange(0,3)];

Clearly, "d" is not contained in the string "abc." I'd like to be able to do this:

if(the range is empty since "d" is not in "abc")
   //do something

What is the code for this?

Thanks!!

like image 300
CodeGuy Avatar asked Aug 17 '10 15:08

CodeGuy


2 Answers

From the documentation of NSString

-[NSString rangeOfString]

Return Value

An NSRange structure giving the location and length in the receiver of the first occurrence of aString. Returns {NSNotFound, 0} if aString is not found or is empty (@"").

So it looks like:

if ([@"abc" rangeOfString:@"d"].location == NSNotFound){
  //Do something

Is the Apple-approved way.

EDIT:

I made a really bad typo, fixed it, thanks Kalle.

like image 86
Jared Pochtar Avatar answered Oct 15 '22 11:10

Jared Pochtar


Check the length of the range. If it's non-zero, it was found.

like image 27
Matt Long Avatar answered Oct 15 '22 11:10

Matt Long