35

I have some string name and I want to compare whether that string contains substring like "_thumb.png".

vikingosegundo
  • 52,040
  • 14
  • 137
  • 178
Devang
  • 11,258
  • 13
  • 62
  • 100
  • Please check the more complete answer to this here: http://stackoverflow.com/questions/2753956/string-contains-string-in-objective-c – TCB13 Jun 13 '13 at 20:45

6 Answers6

64
[string rangeOfString:string1].location!=NSNotFound

rangeOfString: documentation.

unexpectedvalue
  • 6,079
  • 3
  • 38
  • 62
16

You can try this:

NSString *originalString;
NSString *compareString;

Let your string be stored in originalString and the substring that you want to compare is stored in compareString.

if ([originalString rangeOfString:compareString].location==NSNotFound)
{       
    NSLog(@"Substring Not Found");  
}
else
{
    NSLog(@"Substring Found Successfully");
}
Pekka
  • 442,112
  • 142
  • 972
  • 1,088
Gypsa
  • 11,230
  • 6
  • 44
  • 82
3

ssteinberg's answer looks pretty good, but there is also this:

NSRange textRange;
textRange =[string rangeOfString:substring];

if(textRange.location != NSNotFound)
{

//Does contain the substring
}

which I found here.

Eric Brotto
  • 53,471
  • 32
  • 129
  • 174
2
NSString *string = @"hello bla bla";
if ([string rangeOfString:@"bla"].location == NSNotFound)
{
    NSLog(@"string does not contain bla");
}  
else 
{
    NSLog(@"string contains bla!");
}
P.J.Radadiya
  • 1,493
  • 1
  • 12
  • 21
Mohit
  • 3,708
  • 2
  • 27
  • 30
1

In ios 8 or OS X 10.10 we can use.

if(![textLine containsString:@"abc"])
{
     [usableLines addObject:textLine];
}
P.J.Radadiya
  • 1,493
  • 1
  • 12
  • 21
Subhash
  • 545
  • 7
  • 11
0

u can go through this

http://objcolumnist.com/2009/04/12/does-a-nsstring-contain-a-substring/

santosh
  • 504
  • 2
  • 6
  • 20