35

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

vikingosegundo
  • 51,574
  • 14
  • 135
  • 174
Devang
  • 11,098
  • 13
  • 61
  • 98
  • 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,049
  • 3
  • 36
  • 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
  • 431,103
  • 135
  • 960
  • 1,075
Gypsa
  • 11,180
  • 6
  • 43
  • 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
  • 51,631
  • 30
  • 126
  • 173
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,402
  • 11
  • 17
Mohit
  • 3,628
  • 2
  • 26
  • 30
1

In ios 8 or OS X 10.10 we can use.

if(![textLine containsString:@"abc"])
{
     [usableLines addObject:textLine];
}
P.J.Radadiya
  • 1,402
  • 11
  • 17
Subhash
  • 537
  • 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