Archive for April, 2009

Does a NSString contain a substring ?

14

Here is a little tip on how to tell if a string contains another string, using the underused data type NSRange.

NSRange gives the starting location and the length of a given value, and is often used with arrays and strings. On this occasion we will use it to find the range of a substring within another string. If the range has a location, it contains the given substring. The following code does just that.

1
2
3
4
5
6
7
8
9
 
NSRange textRange;
textRange =[string rangeOfString:substring];
 
if(textRange.location != NSNotFound)
{
 
//Does contain the substring
}

Making this a case insensitive compare is also very trivial, and can be done by lowercasing both strings

1
2
3
4
5
6
7
8
9
10
 
NSRange textRange;
textRange =[[string lowercaseString] rangeOfString:[substring lowercaseString]];
 
if(textRange.location != NSNotFound)
{
 
//Does contain the substring
 
}

Hello and Welcome

0

Welcome to my blog about Cocoa programming and all things Apple. I’ll warn you this is going to get very geeky :)

Go to Top